Haskell - putStr vs putStrLn and instruction order

Say we have a short haskell program:

main = do putStr "2 + 2 = "
          x <- readLn
          if x == 4
             then putStrLn "Correct"
             else putStrLn "Wrong"

What result does he produce?

4

2 + 2 = Correct

Now, let's do it again:

main = do putStrLn "2 + 2 = "
          x <- readLn
          if x == 4
             then putStrLn "Correct"
             else putStrLn "Wrong"

It creates

2 + 2 =

4

Right

If bold 4 is entered by the user.

Can someone familiar with Haskell explain to me why this is so? And how do I get the desired result, which

2 + 2 = 4

Right

+4
source share
1 answer

Line buffering. The output buffer is not flushed until a complete line of text is written.

Two solutions:

  • Manually flush the buffer. ( putStr, and then hFlush stdout.)
  • Disable buffering. ( hSetBuffering stdout NoBuffering.)
+10

Source: https://habr.com/ru/post/1527456/


All Articles