[Haskell-beginners] System.IO.withFile
Rafael Gustavo da Cunha Pereira Pinto
RafaelGCPP.Linux at gmail.com
Tue Jan 20 07:20:41 EST 2009
Thanks Antoine!
I was suspecting it should be the lazyness of hGetContents yesterday, before
going to sleep.
You just confirmed that for me!
On Tue, Jan 20, 2009 at 01:44, Antoine Latter <aslatter at gmail.com> wrote:
> 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
>
--
Rafael Gustavo da Cunha Pereira Pinto
Electronic Engineer, MSc.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090120/67de0e2e/attachment.htm
More information about the Beginners
mailing list