A Simple Lazy Sequence
To start with, let's consider the simplest possible producer of lazy sequences, the range
function, which simply returns a possibly infinite series of consecutive integers. The easiest way to write this is to use iterate
:
(defn iterate-range [] (iterate inc 0))
Here, iterate
returns a sequence that starts with the initializer value, zero, and then continues with the result of calling inc
on zero, then on the result of that and so on. Each intermediate value becomes an item in the returned lazy sequence. It works just fine:
user> (take 5 (iterate-range)) (0 1 2 3 4)
The iterate
function is doing all the work. We could stop here, but we wouldn't have learned much about how lazy sequences are built. Here's a more low-level version that performs the same task. It uses the lazy-seq
macro, which is the base of all lazy sequences:
user> (defn our-range [n]         (lazy-seq    ...