[Haskell-beginners] A first try

David Place d at vidplace.com
Sun Jun 26 21:02:07 CEST 2011

On Jun 26, 2011, at 1:29 PM, Manfred Lotz wrote:

> When I stumbled upon lazy IO newbie-wise I was pointed to withFile
> resp. bracket by Daniel Fischer and now that I know how to do it it
> seems fine to me. It also alerted me to pay more attention to lazyness
> as this is a Haskell immanent thingie. 

Of course, it is possible to use hGetContents with withFile.  You can still get into trouble because hGetContents is unsafe.  Beginners get tripped up trying to do something like the following getting unexpected results. (i remember I did.)

print10 = 
       contents <- withFile "/usr/share/dict/words" ReadMode (\h -> hGetContents h)
       print $ take 10 contents

So, you have to do this keeping in mind a rather procedural model of the evaluation of the lazy data structures.  I feel this is not very declarative or intuitive.

print10' = 
       h <- openFile "/usr/share/dict/words" ReadMode
       contents <- hGetContents h
       print $ take 10 contents
       hClose h

Iteratee IO provides a declarative way to do this that is safe, compositional and efficient.  But not yet very pretty.  In haskell cafe, John Lato says that he is working on that.

David Place   
Owner, Panpipes Ho! LLC
d at vidplace.com

More information about the Beginners mailing list