IO monad and lazy evaluation

Glynn Clements glynn.clements@virgin.net
Fri, 23 May 2003 19:34:18 +0100


Ketil Z. Malde wrote:

> >> Thanks for your comments.  (I had overlooked "readFile", which certainly 
> >> looks safer.)
> 
> > It isn't:
> 
> > readFile        :: FilePath -> IO String
> > readFile name	=  openFile name ReadMode >>= hGetContents
> 
> Is too!
> 
> IMHO, the difference is that the program doesn't get the handle to
> mess with, so there's no chance of doing something unexpected (like
> closing it before all required input is read).

OK; it does solve the "premature close" issue, which is what started
this thread. It also ensures that the stream isn't a socket, which
eliminates another class of problems.

I suppose that there could theoretically be issues if readFile was
used on a device or FIFO (named pipe). If you know that you are
accessing such, you probably know about any related issues, but what
if the filename is taken from the command line, and the user specifies
a device or FIFO?

> You still risk somebody messing with the file behind your back, but I
> don't see how strictness changes that.

Strictness won't solve the problem where a completely unrelated
process modifies the file; you would need to use locking for that
(although locking would itself require the use of strict I/O). 
However, with lazy I/O, there could be issues if the modification is
triggered in some way by the reading process.

-- 
Glynn Clements <glynn.clements@virgin.net>