[Haskell-beginners] Buggy behavior of "withFile"

Christopher Reichert creichert07 at gmail.com
Tue Dec 9 20:34:11 UTC 2014


On Tue, Dec 09 2014, Zoran Plesivčak <zplesiv at gmail.com> wrote:
> 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%3awithFile

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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 818 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20141209/fb545600/attachment.sig>


More information about the Beginners mailing list