IO confusion

Simon Marlow simonmar@microsoft.com
Wed, 18 Dec 2002 14:51:48 -0000


> With "Foo" in the file c.out and the module
>=20
> \begin{code}
> module Main (main) where
>=20
> import IO (openFile, hGetContents, hClose, IOMode(ReadMode))
> import System (getArgs)
> import Monad (when)
>=20
> main :: IO ()
> main =3D do [x] <- getArgs
>           let you_want_it_to_work =3D read x
>           cout <- openFile "c.out" ReadMode
>           s <- hGetContents cout
>           putStrLn ""
>           when you_want_it_to_work $ putStrLn $ "Got this: " ++ s
>           putStrLn ""
>           hClose cout
>           putStrLn $ "The answer is: " ++ s
> \end{code}
>=20
> I expected "The answer is: Foo" to be printed whether the argument was
> True or False. When it is False, however, GHC (5.02.2, 5.04 and recent
> CVS HEAD) think s is the empty string and nhc98 (1.10 and a 1.11
> from about a year ago) produces a binary that segfaults. At first I
> thought it was a GHC bug, but now nhc98 also exhibits it I am=20
> wondering if it is a bug in my understanding?

Lazy I/O strikes again :-)

When the argument is True, you should get

   Got this: Foo

   The answer is: Foo

and when the argument is False, one possible correct output is:

   The answer is:

which GHC (5.04.2 and CVS HEAD) does indeed produce.  Another correct
output would be

   The answer is: Foo

in fact, any prefix of "Foo", including the empty string, would be
correct.  See section 21.2.2 in the (revised) Haskell 98 report.

Cheers,
	Simon