[Haskell-beginners] A first try

Heinrich Apfelmus apfelmus at quantentunnel.de
Mon Jun 27 15:32:37 CEST 2011


David Place wrote:
> On Jun 27, 2011, at 3:50 AM, Heinrich Apfelmus wrote:
> 
>> Good point, but this actually shows that  withFile  should be even lazier. In particular:
>>
>> * The file should not be opened until the string is demanded.
>> * The file should be closed as soon as the string has been demanded in full.
> 
> Suppose the file is only partially demanded as in the case I quoted earlier.
> 
> print10 = 
>      do
>        contents <- withFile "/usr/share/dict/words" ReadMode (\h -> hGetContents h)
>        print $ take 10 contents
> 
> The file would never be closed.

Note that my version of  withFile  has a different type and replaces 
hGetContents  entirely.

Regardless, in both cases the intention is that the file contents is 
evaluated completely *inside* the scope of  withFile . In particular, a 
correct way to write your example would be

     print10 = withFile' "/usr/share/dict/words" $ print . take 10

(This is completely analogous to how Iteratees require you to process a 
file. The difference is that Iteratees expresses demand for the 
characters inside a file via  >>=  whereas lazy IO expresses demand via 
`seq` .)


Best regards,
Heinrich Apfelmus

--
http://apfelmus.nfshost.com




More information about the Beginners mailing list