Haskell Syntax and I / O

I played 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 result that I expect:

 Please enter your name: John Doe Hello, John! 

This works as expected when I load the program in ghci. However, when I compile the program using

 ghc -o hello.exe hello.hs 

it starts, waits for input, and then prints both requests at the same time:

 John Doe Please enter your name: Hello, John! 

Why is the behavior different from the interactive environment and the compiler, and how to get the compiler to do what I want?

Thanks in advance for your help!

+4
source share
1 answer

This is something like a FAQ. Your lines are buffered. Using:

 import System.IO main = do hSetBuffering stdout NoBuffering ... 

Also, your code is a little ... unique. For example, you say:

 hstring <- return $ hello name putStr hstring 

When you can do:

 let hstring = hello name putStr hstring 

or simply:

 putStr $ hello name 
+8
source

All Articles