[Haskell-cafe] getContents and lazy evaluation

Tamas K Papp tpapp at Princeton.EDU
Fri Sep 1 15:19:08 EDT 2006


Hi,

I am newbie, reading the Gentle Introduction.  Chapter 7
(Input/Output) says

  Pragmatically, it may seem that getContents must immediately read an
  entire file or channel, resulting in poor space and time performance
  under certain conditions. However, this is not the case. The key
  point is that getContents returns a "lazy" (i.e. non-strict) list of
  characters (recall that strings are just lists of characters in
  Haskell), whose elements are read "by demand" just like any other
  list. An implementation can be expected to implement this
  demand-driven behavior by reading one character at a time from the
  file as they are required by the computation.

So what happens if I do

contents <- getContents handle
putStr (take 5 contents) -- assume that the implementation 
       	       		 -- only reads a few chars
-- delete the file in some way
putStr (take 500 contents) -- but the file is not there now

If an IO function is lazy, doesn't that break sequentiality?  Sorry if
the question is stupid.

Thanks,

Tamas


More information about the Haskell-Cafe mailing list