[Haskell] the wonders of lazy IO

Cale Gibbard cgibbard at gmail.com
Mon Apr 18 22:11:06 EDT 2005

The action readFile is a bit unsafe in that it does lazily interleaved
IO -- that is, the file is read as you consume the string, and only
the part of the string which you use will be read from the file -- if
the file is 10G, but you only end up needing the first 100K of it, or
only need to consume it a small bit at a time, this is great. On the
other hand, if you want a record of the file's contents to be copied
into memory before other modifications take place, it doesn't work.

What you can do is to force the evaluation of the string before
anything else takes place.

Defining something like
force u = do a <- u
             return $! a

and then replacing readFile "foo" with force (readFile "foo") will
result in the program working in the way that you probably expected.

Hope this helps,
 - Cale

On 4/18/05, Johannes Waldmann <waldmann at imn.htwk-leipzig.de> wrote:
> it took me quite a while to isolate the following.
> what does this program print? certainly "A"
> (written by the first system call) is different from "B"?
> import System
> main = do
>      system "echo A > foo"
>      a <- readFile "foo"
>      system "echo B > foo"
>      b <- readFile "foo"
>      print (a == b)
> best regards,
> --
> -- Johannes Waldmann -- Tel/Fax (0341) 3076 6479/80 --
> ---- http://www.imn.htwk-leipzig.de/~waldmann/ -------
> _______________________________________________
> Haskell mailing list
> Haskell at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell

More information about the Haskell mailing list