closing file handles
Simon Marlow
simonmar@microsoft.com
Mon, 10 Sep 2001 11:19:10 +0100
> Tom Pledger wrote:
> > [...]
> > go' f
> > =3D do h <- openFile f ReadMode
> > text <- hGetContents h
> > case text of
> > (c:_) -> do hClose h
> > return c
> >
> > This way, the pattern match on `text' happens before the innermost
> > `do', which in turn closes the handle before letting the rest of the
> > computation continue.
>=20
> I think the above code will lead to problems if file input is=20
> done when c is evaluated and not earlier.
Fortunately, in GHC this isn't the case. Evaluating the (:) is enough
to force the character to be read. But to be on the safe side you could
also write it like this:
go' f
=3D do h <- openFile f ReadMode
text <- hGetContents h
let c =3D head text
c `seq` do { hClose h; return c }
Cheers,
Simon