[Haskell-beginners] Confused about lazy IO

Jacek Dudek jzdudek at gmail.com
Thu Mar 14 23:52:43 CET 2013


Q: When trying to compose the following IO actions:

readFile fileName >>= \ contents ->
writeFile fileName (f contents)

I get an exception: openFile: permission denied.
However the following works:

readFile fileName >>= \ contents ->
(mapM_ putStrLn . lines) contents >>
writeFile fileName (f contents)

I'm assuming it has something to do with lazy IO, and the second
action in the second version forces fileName to be read completely and
to be closed.

Why do I need to do that? I thought lazy IO was implemented in such a
way that you were safe to INTERPRET the IO action as having been fully
performed. (And so I would have been safe to interpret that, in the
first version, in the first action, the file was released.)

If that's not the case, then:
(1) What is the proper way to reason about lazy IO?
(2) Is there some action less arbitrary that what I cooked up in the
second version that explicitly instructs to release a file or some
other resource?

Regards, Jacek.



More information about the Beginners mailing list