Haskell - putStr vs putStrLn and instruction order

haskell, io, output

Solution

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

Two solutions:

- Manually flush the buffer. (`putStr` followed by `hFlush stdout`.)

- Turn off buffering. (`hSetBuffering stdout NoBuffering`.)

Problem

Let's say we have a short haskell programm: ``` main = do putStr "2 + 2 = " x <- readLn if x == 4 then putStrLn "Correct" else putStrLn "Wrong" ``` What output does it produce? 4 2 + 2 = Correct Now let's have another: ``` main = do putStrLn "2 + 2 = " x <- readLn if x == 4 then putStrLn "Correct" else putStrLn "Wrong" ``` That produces 2 + 2 = 4 Correct Where the bold 4 is user-inputted. Could anybody familiar with Haskell explain to me why that is? And how do I get the desired result, which is 2 + 2 = 4 Correct

Original source

Related problems