Incomplete output when hPutStr is lifted

andrew cooke andrew at acooke.org
Thu Nov 27 16:09:00 EST 2003


Hi,

If I compile and run the code below, the file "foo" contains 10 lines
of output (as I would expect), but the file "bar" contains just 9 -
the final line is missing.  If I add a "join", as in the comment, then
all 10 lines appear.

I don't understand why, completely - my best guess is that it's
related laziness and the final result of the fold not being used.
However, in that case, I'm worried that the "join fix" isn't
guaranteed to work.

Please could someone explain what is happening and how I should
guarantee that the output is "complete".

Thanks,
Andrew

$ cat test.hs

main :: IO()
main = do h <- openFile "foo" WriteMode
          foldM (printer h) 1 [1..10]
          hClose h
          h <- openFile "bar" WriteMode
          foldM (liftM2 (printer h)) (return 1) $ map return [1..10]
--          join $ foldM (liftM2 (printer h)) (return 1) $ map return [1..10]
          hClose h

printer :: Handle -> Int -> Int -> IO Int
printer h n i = do hPutStr h (show n)
                   hPutStr h ":"
                   hPutStr h (show i)
                   hPutStr h "\n"
                   return (n+1)

$ ghc test.hs
$ ./a.out
$ diff foo bar
10d9
< 10:10

-- 
personal web site: http://www.acooke.org/andrew
personal mail list: http://www.acooke.org/andrew/compute.html


More information about the Haskell mailing list