Being Lazy

Many Clojure algorithms use lazy evaluation, where the operations aren’t performed unless their result actually needs to be evaluated. Laziness is crucial for making many algorithms work efficiently. For example, you might think the preceding example is very inefficient since we have to iterate over the sequence each time to create the range, map across it, interpose the numbers, and reduce the result.

However, this is not actually the case. The evaluation of each expression happens on demand. The first value in the range is generated and passed to the function, then the next, and so on, until the sequence is exhausted. This is similar to the approach that languages like Python take with their iterator mechanics.

Get Web Development with Clojure, 2nd Edition 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.