[Haskell] space behaviour of lazy recursive lists

Axel Jantsch axel at ele.kth.se
Sun Jan 30 11:00:09 EST 2005


Hi,

How can I get constant space behaviour for lazy, recursive streams?

Consider:

> gibs = 1 : 1 : (zipWith f gibs (tail gibs))
>        where f x y = min (x + y) 10

This is derived from the fibs text book example, modified to bound the
memory requirement for each list element.

Evaluating gibs should require constant amount of memory, since the
computed parts of the list are not needed any more and can be reclaimed.

However, hugs says:

Main> nth 100 fibs
  10
  (2818 reductions, 3730 cells, 1 garbage collection)

Main> nth 200 fibs
  10
  (5618 reductions, 7430 cells, 1 garbage collection)

which suggests linear space behaviour. Also, ghc shows the same behaviour
with a linearly growing stack size as shown by the profiler (+RTS -hc -xt)
and sooner or later the program runs out of memory with a stack overflow. 

It seems the entire list up to the last evaluated element is stored. Since
I want to use lazy streams to simulate process networks, I want to run the
simulation arbitrarily long without *ever* running out of memory. 

So my question is, how can I process recursive, lazy streams in constant
space? 

Or, in other words, how can I force the garbage collector to reclaim the
memory of the head of the list after I have processed it, since I will
never ever reference it again?

With best regards
Axel Jantsch


---
Phone: +46 8 790 4124, Email: axel at imit.kth.se, Web: www.imit.kth.se/~axel


More information about the Haskell mailing list