[Haskell-beginners] System.IO.withFile

Antoine Latter aslatter at gmail.com
Mon Jan 19 22:44:56 EST 2009


On Mon, Jan 19, 2009 at 7:30 PM, Rafael Gustavo da Cunha Pereira Pinto
<RafaelGCPP.Linux at gmail.com> wrote:
> Could someone explain why:
>
> main= do
>               h<-openFile "test.cir" ReadMode
>               c<-hGetContents h
>               print c
>
>> runhaskell test1.hs
>> "* Teste\n\nR1  1 0 10\nC1  1 0 10uF\nI1  1 0 1mA\n\n.DC \n.PRINT\n"
>
> works and
>
>
> main= (withFile "test.cir" ReadMode hGetContents) >>= print
>
>> runhaskell test1.hs
>> ""
>
> don't?

'hGetContents' is a lazy-IO function, which means doesn't really start
reading from the handle until another function tries to consume its
output.

The problem is that 'print' - the consumer - is outside of the
'withFile' argument, and 'withFile' guarantees that the file is closed
when it finishes execution.

So by the time 'hGetContents' tries to do its thing, the file handle is closed.

This snippet:

> main = withFile "test.cir" ReadMode $ \h -> hGetContents h >>= print

puts the call to 'print' inside the argument to 'withFile', so it
should work as expected.

-Antoine


More information about the Beginners mailing list