Lazy evaluation of terms in an infinite list in Haskell

This is a self-referential, lazy data structure, where “later” parts of the structure refer to earlier parts by name.

Initially, the structure is just a computation with unevaluated pointers back to itself. As it is unfolded, values are created in the structure. Later references to already-computed parts of the structure are able to find the value already there waiting for them. No need to re-evaluate the pieces, and no extra work to do!

The structure in memory begins as just an unevaluated pointer. Once we look at the first value, it looks like this:

> take 2 fibs

enter image description here

(a pointer to a cons cell, pointing at ‘1’, and a tail holding the second ‘1’, and a pointer to a function that holds references back to fibs, and the tail of fibs.

Evaluating one more step expands the structure, and slides the references along:

enter image description here

And so we go unfolding the structure, each time yielding a new unevaluated tail, which is a closure holding references back to 1st and 2nd elements of the last step. This process can continue infinitely 🙂

And because we’re referring to prior values by name, GHC happily retains them in memory for us, so each item is evaluated only once.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)