0

I was playing around in Haskell and noticed something weird. I've defined a simple prompt function below.

-- file: test.hs
main :: IO ()
main = putStrLn . ("Hello, " ++) =<< (putStr "Name: " >> getLine)

When I runhaskell this, it works as expected, printing the prompt, waits for my input, then prints the greeting.

$ runhaskell test.hs
Name: kwarrtz
Hello, kwarrtz

When I compile it, however, things get weird. When I run it, it doesn't print the prompt, instead giving me a blank line and waiting for input. When I type my name and hit enter, it prints the prompt and the greeting, on the same line. In otherwords, the getLine happens before the putStr.

$ ghc test.hs
$ ./test
kwarrtz
Name: Hello, kwarrtz

Any thoughts on what's happening? I imagine it has something to do with the line buffering on my terminal, but I'm not sure how (that or I've just made some really ridiculous mistake in my code).

I'm running GHC 7.8.3 on Mac OS X El Capitan and using the default Terminal app.

Kwarrtz
  • 2,693
  • 15
  • 24

1 Answers1

7

Buffering.

hSetBuffering stdout NoBuffering

I think you can get all that from System.IO

luqui
  • 59,485
  • 12
  • 145
  • 204
  • To expand a little: as in some other languages, output is buffered, and is not really sent to the OS until a newline, or an explicit flush operation happens. (It is sad though, that `runhaskell` and compiling the code use different buffering -- they should be more consistent IMHO) – chi Nov 23 '15 at 10:44
  • @chi Is there are reason that `runhaskell` and `ghc` use different buffering modes, or is it just an unintentional inconsistency? – Kwarrtz Nov 25 '15 at 01:19
  • @Kwarrtz I can't think of any reason. – chi Nov 25 '15 at 14:11