Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - putStr vs putStrLn and instruction order [duplicate]

Tags:

io

output

haskell

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

like image 294
User1291 Avatar asked Feb 18 '14 09:02

User1291


1 Answers

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

Two solutions:

  1. Manually flush the buffer. (putStr followed by hFlush stdout.)
  2. Turn off buffering. (hSetBuffering stdout NoBuffering.)
like image 58
MathematicalOrchid Avatar answered Oct 31 '22 14:10

MathematicalOrchid