What is laziness or lazy evaluation?

The idea of laziness or lazy evaluation in programming languages is to make them more efficient. The evaluation process in most programming languages is automatically triggered when a compiler encounters an expression. It gets a piece of code and performs it to generate a result, even though it may not be used. This can consume a lot of memory and waste processing resources. Lazy evaluation is a possibility offered by some programming languages to try to overcome this wastage because it keeps the code without evaluating it unless it’s necessary.

How does Clojure use lazy evaluation?

Clojure is not a lazy language, so we can’t say that it does this process the whole time. But it has lazy sequences, and they’re widely used.

Lazy sequences

The idea of lazily evaluated sequences means that sequence elements are not available all the time and aren’t produced as the result of a computation. The computation is performed as needed and is known as realization.

All collections in Clojure can become a sequence when converted with the core function lazy-seq, enabling them to exhibit this behavior. They can be infinite, with their realization happening as needed, and they can be finite. When the computation of a finite sequence is completed, it becomes fully realized.

We can also think of lazy sequences as unknown collections because we don't know what’s inside until they’re realized.

How can we take advantage of it?

Lazy sequences have the following benefits:

  • They can be infinite.

  • The full realization of interim results can be avoided.

  • They can be used with most of the collection types.

  • There are a lot of very useful core functions that implement lazy sequences.

Producing lazy sequences

We can use the lazy-seq function to produce lazy sequences in many ways—by a function or by another collection type.

Now let’s just take a look at some code that exemplifies exactly what we’ve learned so far, and let’s use the lazy-seq function to create a lazy sequence.

Get hands-on with 1200+ tech skills courses.