Lazy and Infinite Sequences

Most Clojure sequences are lazy; in other words, elements are not calculated until they’re needed. Using lazy sequences has many benefits:

  • You can postpone expensive computations that may not in fact be needed.
  • You can work with huge data sets that don’t fit into memory.
  • You can delay I/O until it’s absolutely needed.

Consider the code and following expression that produces (mostly) prime numbers using wheel factorization:[19]

 (ns examples.primes)
 ;; Taken from clojure.contrib.lazy-seqs
 ; primes cannot be written efficiently as a function, because
 ; it needs to look back on the whole sequence. contrast with
 ; fibs and powers-of-2 which only need a fixed buffer of 1 or 2
 ; previous ...

Get Programming Clojure, 3rd 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.