liveBook · Manning

Cons

As explained in Clojure: The Essential Reference

cons is a Clojure function that constructs a sequence by adding an element to the front of an existing sequence.

cons constructs a sequence by linking one element to the front of a sequential tail. The result remains sequential, so it can be passed to another cons to extend the chain. section 9.4.2

Use cons with these contract and behavior details:

  • Accepts any value as its first argument and a sequential collection or nil as its second. section 9.4.2
  • Returns a clojure.lang.Cons containing the new first element and the original tail; with nil, returns a PersistentList instead. section 9.4.2
  • Throws IllegalArgumentException when the tail is not sequential, often indicating that conj and cons arguments were confused. section 9.4.2
  • Builds linked chains, but large concrete cons structures are generally discouraged; cons is primarily a building block for lazy sequences. section 9.4 section 9.4.2

Prepending and composing

(cons :a [1 2 3]) ;; (:a 1 2 3) (cons 1 (cons 2 (cons 3 (cons 4 ())))) ;; (1 2 3 4) For longer chains, list* provides a more compact form: (list* 1 2 3 4 5 ()) produces (1 2 3 4 5).

Generating a lazy sequence

A recursive lazy-seq can use cons to emit the current item and defer the rest: (defn lazy-loop [xs] (lazy-seq (when-first [x xs] (cons x (lazy-loop (rest xs)))))) (last (lazy-loop (range 100000))) ;; 99999 Replacing cons with conj in this pattern produces StackOverflowError.

How Clojure: The Essential Reference covers it

How deep it goes
Explains inputs, output types, linked-cell structure, invalid tails, and lazy construction examples.
Examples
Demonstrates prepending to a vector, nesting cons calls, using list*, and recursively generating a lazy sequence.
What it assumes
Requires understanding sequential collections or nil as the tail; distinguishes these inputs from arbitrary collections.
What you can do after
Build lazy sequences and linked sequence chains while recognizing valid tails and the cons-conj distinction.
How it connects
Connects cons with lists, list*, sequences, lazy sequences, and conj.

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.