
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
On Mon, Jan 19, 2009 at 7:30 PM, Rafael Gustavo da Cunha Pereira Pinto
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.