An IO Question from a Newbie

Jon Cast jcast at
Sun Sep 21 22:02:57 EDT 2003

> On Fri, 12 Sep 2003 16:27:59 -0600
> Matt O'Connor <angagon at> 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  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.

Just thought I'd point out (in case it isn't clear) that this function
is flushAfter h a = liftM2 const a (hFlush h).  Not much of an

Jon Cast

More information about the Haskell-Cafe mailing list