How to write a lazy variant ?

Dmitry Astapov
05 Dec 2001 01:53:37 +0200

 DA> Consider the following functions:

 DA> readRecFile fname =
 DA>     do ifh <- openFile fname ReadMode
 DA>        readRecords ifh

 DA> readRecords ifh =
 DA>     do x <- decodeNextRecord ifh
 DA>        more  <- isEof ifh
 DA>        if (more == False) 
 DA>          then return [x]
 DA>          else do rest <- readRecords ifh
 DA>                  return (x:rest)

 DA> They allow me to read contest of file fname into a list of data
 DA> structures. But "do rest <- readRecords ifh ; return (x:rest)" part makes
 DA> them behave non-lazily. Maybe I'm just too tired right now, but it escapes
 DA> me how can I write a lazy variant of those functions, so that they will
 DA> behave like getContents. Does anyone have a clue?

I hate to followup to myself, but looks like I had to. I really was too
tired and lazy version could be obtained by simple use of accumulator:

> readRecFile fname =
>     do ifh <- openFile fname ReadMode
>        readRecords ifh []

> readRecords ifh acc =
>     do x <- decodeNextRecord ifh
>        more  <- isEof ifh
>        if (more == False) 
>          then return (x:acc)
>          else do readRecords ifh (x:acc)

That's it.

Sorry for noice on the list.

Dmitry Astapov //ADEpt                               E-mail:
GPG KeyID/fprint: F5D7639D/CA36 E6C4 815D 434D 0498  2B08 7867 4860 F5D7 639D