Cons seq, a basic seq type.

A cons object consists of head (first) item and of a tail (rest of the collection). Cons does not care what the tail is as long as it is ISeq. Moreover, cons objects are not counted (calling count on them is not efficient), never empty and are not a persistent stack, as pop cannot guarantee to return IStacked seq.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
(cons 1 nil)
;;=> (1)

(cons 1 ()) ;; not idiomatic!
;;=> (1)

(cons 1 (cons 2 (cons 3 nil)))
;;=> (1 2 3)

(cons 1 [2 3]) ;; implicit call to seq
;;=> (1 2 3)

;;; cons does not realize lazy seqs, not even to check if the lazy seq is empty or not

(def x (cons 1 (seq (range))))
;;=> #'foo.bar/x

;;; cons objects do not support pop

(pop (cons 1 (cons 2 (cons 3 nil))))
;;=> No implementation of method: :-pop of protocol: #'dunaj.coll/IStacked found for class: clojure.lang.Cons

cons

Available since version 1.0 (alias of clojure.core/cons)

Usage:
  • (cons x coll)

Type signature:
  • (Any ⨯ []) → Cons

Returns a new seq where x is the first item and coll is the rest. Calls seq on coll if it is not already a seq.

cons is not polymorphic and will always return a seq. Use conj if you want to preserve the characteristics of coll.