order of computation in 'do' notation

Hi, I have to hand in my final project for my degree next week. I've been running my program through hugs most of the time, and I wanted to compile it to an executable, so I used ghc. Unfortunately ghc makes the program behave in a different, undesirable way. The code where the problem lies is shown below. Basically, in hugs, the prompt ">> " is displayed and then it waits for a command to be entered (getCommand) - which is what I want, but 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! I'd be very grateful for any suggestions as to how to fix this. thanks, Rich. mainLoop :: IO TRS -> IO () mainLoop t = do putStr "\n>> " (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... And then the getCommand function is as follows: -- gets a command from the standard input getCommand :: Int -> IO (String,String) getCommand _ = do com <- getLine return (splitComm com) -- splits a command into the main command and arguments splitComm :: String -> (String,String) splitComm [] = ("","") splitComm (' ':cs) = ("",cs) splitComm (c:cs) = ((c:rest),rem) where (rest,rem) = splitComm cs

NOTE: Even the examples are correct in the H98 libraries documentation in the IO module section, they are incorrect in the H98 Report: http://www.haskell.org/onlinereport/io-13.html Scroll down, to 7.2. <snip>
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 you're waiting for input in stdin*, IMO it should be. IIRC this was a change that happened between the somwhere between 5.00.1 and 5.02.2. I remember suddenly 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 = 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. J.A.
participants (2)
-
Jorge Adriano
-
Rich