LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Haskell: I/O Not in Order? (https://www.linuxquestions.org/questions/programming-9/haskell-i-o-not-in-order-875718/)

hydraMax 04-18-2011 04:38 PM

Haskell: I/O Not in Order?
 
Hi. I'm learning Haskell from an on-line tutorial, and trying to figure out how I/O works. I'm a bit confused with this example:

Code:

import Control.Monad
import Data.Char

main = forever $ do
    putStr "Next line: "
    l <- getLine
    putStrLn $ map toUpper l

My expectation is for it to ask me for a line, then for it to convert the line I provide to uppercase (err... create a new line that is uppercase) and then output said line.

However, what actually happens when I run it is it firsts ask me for a line, then outputs "Next line: ", then outputs the uppercase line:

Code:

$ ghc forever-example.hs -o forever-example
$ ./forever-example
Hi there
Next line: HI THERE
More of my input
Next line: MORE OF MY INPUT
and so on
Next line: AND SO ON

I realize that Haskell is not an imperative language, but I was (mistakenly?) under the impression that there was some kind of sequence guaranteed in the do blocks. Could someone explain why this happens, and how I can "fix" my code to get the desired behavior?

I'm running:
- Linux version 2.6.34-gentoo-r12 (64-bit)
- GNU bash, version 4.1.9(2)-release (x86_64-pc-linux-gnu)
- Glasgow Haskell Compiler, Version 6.12.3, for Haskell 98, stage 2 booted by GHC version 6.12.3

jeff_sadowski 04-18-2011 05:23 PM

This would be better answered form the makers of ghc.

wje_lq 04-18-2011 07:02 PM

I don't have Haskell on my system and know nothing about it, and you didn't give a link to your tutorial, but just looking around, I'd suggest you change
Code:

putStr
to
Code:

putStrLn
That should fix this symptom.

So the next question is: how do you fix it so that the prompt and the keyed input appear on the same line? Dunno. Don't know Haskell. Sorry.


All times are GMT -5. The time now is 05:45 PM.