Emacs Lisp: Cons Pair

By Xah Lee. Date: . Last updated: .

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 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 First/Last of cons Pair

(car cons_pair)
Get the first element of a (cons a b) pair.
(cdr cons_pair)
Get the last element of a (cons a b) pair.
(setq xx (cons 3 4))

;; get first element
(car xx) ; 3

;; get last element
(cdr xx) ; 4

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 "a" "b" "c")

it is identical to

(cons "a" (cons "b" (cons "c" nil)))

Dot Notation '(a . b)

(cons a b) has a syntax shortcut '(a . b)

;; all true

(equal (cons 3 4)
       '(3 . 4))

(equal (cons 3 4)
       (quote (3 . 4)))

Proper List

Lisp Data Structure


Lisp Basics

Basics

Lisp Data Structure

Function

Lisp Symbol

Lisp Misc

Working with Elisp