ELisp: Cons Pair

By Xah Lee. Date: . Last updated: .

What is Cons Pair

cons pair (aka cons cell or just cons) is a value type, and is a fundamental data structure in emacs lisp. List is made of cons pairs.

cons
(cons val1 val2)

Creates a cons pair structure. This structure is used to make lists.

  • Cons has 2 values, always. Otherwise it's syntax error.
  • The values can be any lisp value type.

Cons Pair Can be Nested in Any Way

For example, the following are all valid:

;; cons can be nested in anyway
;; value can be any lisp value
(cons 2 3)
(cons (cons 2 3) 3)
(cons (cons (cons 2 3) 3) 3)
(cons (cons 2 3) (cons 2 3))
(cons 2 (cons 2 3))
(cons 2 (cons (cons 2 3) 3))
(cons 2 (cons 2 (cons 2 3)))

Cons can also contain nil, because any value is allowed.

(cons nil nil)
(cons 3 nil)
(cons nil 3)

Get Parts of Cons Pair

car
(car consPair)

Get the first element of a cons pair.

(setq xx (cons 3 4))

;; get first element
(car xx) ; 3

;; get last element
(cdr xx) ; 4
cdr
(cdr consPair)

Get the last element of a cons pair.

Note: The weird names {car, cdr, cons} are like that for historical reasons.

List is Made of Cons

All lisp lists are built from cons. For example, this list:

(list 1 2 3)

it is identical to

(cons 1 (cons 2 (cons 3 nil)))

Proper List

Emacs Lisp List

Special Lists

List Structure