liveBook · Manning

Lazy-cat

As explained in Clojure: The Essential Reference

lazy-cat is a Clojure macro that lazily concatenates collections without evaluating its arguments in advance.

lazy-cat is a Clojure macro for concatenating collections lazily. It wraps each argument in lazy-seq before passing the result to concat, so arguments are not evaluated in advance. section 9.3.9

Use lazy-cat when:

  • Only the portion requested by a consumer should be realized. section 9.3.9
  • Collections have different creation costs and later collections should not be built unnecessarily. section 9.3.9
  • You need a lazy sequence combining sequential collections or nil; invalid non-sequential inputs can raise IllegalArgumentException. section 9.3.9

Avoiding unnecessary work

(time (first (lazy-cat (vec (range 10)) (vec (range 1e7))))) ;; "Elapsed time: 0.313782 msecs" The first result can be produced without eagerly processing the large second collection.

Infinite sequences

(def fibs (lazy-cat [0 1] (map +' fibs (rest fibs)))) (take 10 fibs) ;; (0 1 1 2 3 5 8 13 21 34)

How Clojure: The Essential Reference covers it

How deep it goes
Explains laziness, input contracts, exceptions, and macroexpansion, but does not detail the underlying sequence implementation.
Examples
Demonstrates timing, macroexpansion, infinite Fibonacci generation, and deferred tracing of collection elements.
What it assumes
Assumes familiarity with Clojure sequences and concat while demonstrating lazy evaluation through examples.
What you can do after
Apply it via Clojure to build lazy concatenations that avoid unnecessary collection construction.
How it connects
Connects lazy-cat with concat, lazy-seq, sequences, transducers, and mapcat.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.