[Haskell-beginners] Buggy behavior of "withFile"

Kim-Ee Yeoh ky3 at atamo.com
Fri Dec 12 03:29:03 UTC 2014


On Wed, Dec 10, 2014 at 3:34 AM, Christopher Reichert <creichert07 at gmail.com
> wrote:
>
> Google around for "haskell lazy io withFile" and you might find more
> detailed explanations.
>

Yes indeed. The explanations are pretty good too.

This is a gotcha that deserves to be more widely known. A recent patch to
ghc gives a better error message explaining what's going on.

How does one go about using withFile correctly then?

If you see the code "withFile filename ReadMode" chances are you should
replace it with "readFile filename".

Hence, instead of

main = do
        cnts <- withFile "example.hs" ReadMode $ (\h -> do
            res <- hGetContents h
            --putStr res
            return res)
        putStr cnts

write

main = do
        cnts <- readFile "example.hs"
        putStr cnts

or more idiomatically

main = readFile "example.hs" >>= putStr

-- Kim-Ee
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20141212/5565c033/attachment.html>


More information about the Beginners mailing list