[Haskell] Sequencing of input and output, troubles in kdevelop

Glynn Clements glynn.clements at virgin.net
Fri Aug 27 18:11:40 EDT 2004

A.J. Bonnema wrote:

> I used kdevelop to enter and compile the following code (Haskell):
> module Main where
> main = do putStr "naam invoerbestand?"
> 	  inf <- getLine
> 	  txt <- readFile inf
> 	  putStr "naam uitvoerbestand?"
> 	  outf <- getLine
> 	  writeFile outf txt
> When executed I have to enter the first filename, then the second 
> filename and finally the questions are both asked in one go and the 
> program ends.
> This also happens if I executed the generated binary from an term.
> However, using hugs, I get the first question first, enter the filename, 
> then I get the second question, I enter the filename and then the 
> program ends.
> Why doesn't kdevelop generate code, that executes the statements in 
> order? Or should I be looking at ghc? Or is it an option I am missing?

As others have pointed out, the issue is the buffering.

However, there is another issue which seems to have been overlooked:
you aren't writing newlines, so the stream won't be flushed
automatically even in the stream is line-buffered.

If you use putStrLn instead of putStr, the stream will be flushed
automatically (assuming that it is line-buffered, which is the default
if the stream is associated with a terminal). If you don't want to add
a newline, add explicit hFlush calls, i.e.:

	putStr "naam invoerbestand?"
	hFlush stdout
	inf <- getLine

In C, you don't need to use fflush() in this situation because, when a
read from a line-buffered input stream cannot be fulfilled from the
buffer (i.e. the stdio code has to read() from the underlying
descriptor), all line-buffered output streams are flushed

The Haskell I/O library doesn't mimic this aspect of C, so you have to
add explicit hFlush calls if you want partial lines (strings which
don't end with a newline character) to be displayed immediately.

Glynn Clements <glynn.clements at virgin.net>

More information about the Haskell mailing list