order of computation in 'do' notation

Jorge Adriano jadrian@mat.uc.pt
Thu, 25 Apr 2002 12:14:07 +0100

NOTE: Even the examples are correct in the H98 libraries documentation in=
IO module section, they are incorrect in the H98 Report:
Scroll down, to 7.2.=20

> when I put the same code through ghc, it waits for a command first, and
> then when the command has been entered it displays the prompt, which is
> just silly.  Surely the 'do' notation was designed to sequence
> computations, but it obviously isn't behaving quite right here!

The problem is that stdout is buffered by default and *not flushed when y=
waiting for input in stdin*, IMO it should be. IIRC this was a change tha=
happened between the somwhere between 5.00.1 and  5.02.2. I remember sudd=
all my programs not working correctly anymore...

> I'd be very grateful for any suggestions as to how to fix this.
> thanks,
One way is to *import IO*  and  set stdout to NoBuffering

> mainLoop :: IO TRS -> IO ()
> mainLoop t =3D do putStr "\n>> "
>                 hSetBuffering stdout NoBuffering   -- HERE!!!
>                 (c,a) <- getCommand 0
>                 case c of
>                    "help" -> do putStr help
>                                 mainLoop t
>                    "load" -> do trs <- load a
>                                 putStr ""
>                                 mainLoop (return trs)
>                    "show" -> ...and so on...

You may also flush stdout every time you want using hflush.
Check the haskell libraries documentation for the IO module for more info=