[Haskell-cafe] IO and lazyness.

Daniel McAllansmith dm.maillists at gmail.com
Tue Mar 6 16:35:05 EST 2007


On Wednesday 07 March 2007 10:22, D.V. wrote:
> On 3/6/07, mm <schneegloeckchen at gmx.li> wrote:
> > I cannot help you with your question more than pointing you to
> >
> > http://bugs.darcs.net/issue391
> >
> > where Simon Marlow explains how to avoid "IO.bracket".
>
> I'm using Control.Exception's bracket.
>
> Also, following Jeremy's advice, I replaced the last line of rechf2
> with   return $! rech r $ lines f       and indeed it works.
>
> I don't understand why it doesn't without the !
>
> The documentation for hGetContents says the items are read on demand.
> the function rech needs the strings so they should be read on demand.
> This confuses me :(

The problem is that hGetContents only reads the contents of the file on demand 
and, without the 'return $!' you don't demand the value until somewhere 
outside of rechf.  By this point the hClose has happened and hGetContents has 
no access to the file => no lines => no result.

Using 'return $!' is demanding the value of rech r $ lines f immediately so 
hGetContents accesses the file before the hClose.


hGetContents is implemented using unsafePerformIO so, unless you're very 
careful, you could get other weird behaviours.


Daniel


More information about the Haskell-Cafe mailing list