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.
