An IO Question from a Newbie

Derek Elkins ddarius at hotpop.com
Fri Sep 12 20:17:05 EDT 2003


On Fri, 12 Sep 2003 16:27:59 -0600
Matt O'Connor <angagon at earthlink.net> wrote:

> Hello all.  I'm new to functional programming and Haskell, but have
> been programming in C and Java for a while.  I've been going through
> the tutorials and whatnot on haskell.org.  I've read from the Gentle
> Introduction to Haskell about IO and some of the other stuff and I
> have a question about it.  
> 
> main = do putStr "Type Something: "
>           str <- getLine
>           putStrLn ("You typed: " ++ str)
> 
> When compile and run this code the "Type Something: " isn't displayed
> until the putStrLn.  So there is no prompt.  The output looks like
> this.
> 
> s
> Type Something: You typed: s
> 
> But if I change the putStr "Type Something: " to a putStrLn or put a
> \n at the end of the string it displays the text immediately (ie, when
> I want it to).  Is there a good reason for this?  Am I doing something
> wrong?  Or do I need to call some kind of standard output flush?

Yes, the problem is that the first line is not being flushed.  Importing
hFlush and stdout from IO (or System.IO) and adding hFlush stdout after
you putStr will fix it.  Alternatively, you could change the buffering
on stdout to NoBuffering.  I don't know if there is a standard
putStrWithFlush function or just a better answer than this. A
putStrWithFlush would be trivial to write or more generally to a
HOF that flushed after performing the action passed to it.



More information about the Haskell-Cafe mailing list