
On Tue, Dec 09 2014, Zoran Plesivčak
I've encountered unexplainable of "withFile" function. Consider "example.hs" program:
import System.IO
main = do cnts <- withFile "example.hs" ReadMode $ (\h -> do res <- hGetContents h --putStr res return res) putStr cnts
When commented-out line is like that, program doesn't write out anything to the STDOUT. If "--" (commend characters) are removed, program writes out contents of "example.hs" two times.
Is this expected behavior? I asked on #haskell (freenode) and one fellow there found it equally confusing...
This is an example of where Lazy IO can get tricky. withFile is closing the handle before you are able to evaluate the contents. When you use putStr in the lambda function, `res` is evaluated (and thus evaluated when it's returned). When it's commented, res is not evaluated before you close the file. See the documentation: http://hackage.haskell.org/package/base-4.7.0.1/docs/System-IO.html#v%3awith... Specifically note: "The handle will be closed on exit from withFile" Google around for "haskell lazy io withFile" and you might find more detailed explanations. -- Christopher Reichert irc: creichert gpg: C81D 18C8 862A 3618 1376 FFA5 6BFC A992 9955 929B