Haskell do syntax and I/O
I was playing around with a simple program in Haskell:
hello :: String -> String
hello s = "Hello, " ++ (trim s) ++ "!\n"
trim :: String -> String
trim [] = []
trim s = head $ words s
main :: IO()
main = do putStr "\nPlease enter your name: "
name <- getLine
hstring <- return $ hello name
putStr hstring
This is the output I am expecting:
Please enter your name: John Doe
Hello, John!
This works as expected when I load the program into ghci. However when I compile the program using
ghc -o hello.exe hello.hs
it starts, waits for input, and then prints both prompts at the same time:
John Doe
Please enter your name: Hello, John!
Why is the behavior different between the interactive environment and compiler, and how can I make the compiler do what I want?
Thanks in advan开发者_如何学Pythonce for the help!
This is something of an FAQ. Your lines are being buffered. Use:
import System.IO
main = do
hSetBuffering stdout NoBuffering
...
Also, your code is a bit... unique. For example, you say:
hstring <- return $ hello name
putStr hstring
When you could do:
let hstring = hello name
putStr hstring
or just:
putStr $ hello name
精彩评论