Behind the Scenes

Now that we have a feeling for how lazy sequences work from the outside, let’s look at how they are built. The key tool for building a lazy sequence from scratch is the aptly named lazy-seq. The lazy-seq function is similar to seq. Like with seq, you give lazy-seq an expression and it will turn it into a sequence. So this:

 (lazy-seq [1 2 3])

will give you the three-element sequence (1 2 3). The difference is that lazy-seq, being lazy, will hold off on evaluating the expression until you actually start pulling things off the sequence that it returns. For example, if you wrapped your vector in a chatty function:

 (​defn​ chatty-vector []
  (println ​"Here we go!"​)
  [1 2 3])

and then made a lazy sequence out of it:

 ;; No ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.