[Haskell-cafe] Very Basic IO question

Donald Bruce Stewart dons at cse.unsw.edu.au
Sat Mar 3 02:09:12 EST 2007


olivasj:
> I am VERY new to Haskell, and just getting my feet wet with functional  
> programming in general.  I've been going over a few examples online, but I  
> can't figure out the behavior I'm seeing on a very basic example:
> 
> ---
> module Main where
> 
> import System.IO
> 
> main :: IO ()
> main = do
>         putStrLn "Please enter your name: "
>         name <- getLine
>         putStrLn ("Hello, " ++ name ++ ", how are you?")
> ---
> 
> This example works as I would expect.  The prompt displays with a new  
> line, the input is entered and echoed:
> ---
> Please enter your name:
> joe
> Hello, joe, how are you?
> 
> However, changing 'putStrLn' to 'putStr' does not do what I would expect.   
> The prompt doesn't get displayed until after there is input:
> ---
> joe
> Please enter your name: Hello, joe, how are you?
> 
> Why does it exhibit this behavior?  I'm using a ghc 6.6 built from source  
> from 20070227.  The regular 6.6 release had the same behavior.  Any help  
> would be greatly appreciated.
> 

In short: buffering.
You're not flushing the output buffer till \n appears. 

To ask for no buffering, you would write:

    import System.IO

    main :: IO ()
    main = do
         hSetBuffering stdout NoBuffering
         putStr "Please enter your name: "
         name <- getLine
         putStrLn ("Hello, " ++ name ++ ", how are you?")

Which runs as:

    $ ./a.out 
    Please enter your name: Don
    Hello, Don, how are you?

Cheers,
  Don


More information about the Haskell-Cafe mailing list