0

I am playing with IO monad and learning to harness side effects in Haskell and it seems like I got it wrong.

Consider the following code:

main = do
    putStr "test"
    getLine
    return ()

My understanding here is that do "glues" three IO monads into one. My assumption is that they will be executed in sequence, i.e. "test" will be printed first, then line read, and then dummy return () will produce ()

However, when I run compiled app it always waits for line to be read before printing "test".

Reordering putStr/getLine does nothig. "Unwrapping" value from IO monad, like this:

main = do
    _ <- putStr "test"
    _ <- getLine
    return ()

... does not change the result either.

What am I missing here? How to enforce order on IO actions?

Eugene Loy
  • 12,224
  • 8
  • 53
  • 79
  • 1
    This is probably due to the default line buffering for Haskell. Try adding `import System.IO` at the top of your code, then put `hSetBuffering stdout NoBuffering` before `putStr "test"`. I've seen this get a lot of people (and it got me when I was first starting with Haskell). – bheklilr Jul 02 '15 at 02:52
  • @bheklilr it worked, thanks. Please, post this as an answer, so I could accept it. – Eugene Loy Jul 02 '15 at 03:06
  • I just pointed it back to a very similar question that already has a good accepted answer with more detail that I probably would have put here. – bheklilr Jul 02 '15 at 03:10

0 Answers0