Elisp: Cons Cell
What is Cons Cell
cons cell (aka cons pair or just cons) is a value type, and is a fundamental data structure in emacs lisp. List is made of cons cells.
cons
-
(cons val1 val2)
Creates a cons cell 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 Cell 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 Cell
car
-
(car consCell)
Get the first element of a cons cell.
(setq xx (cons 3 4)) ;; get first element (car xx) ; 3 ;; get last element (cdr xx) ; 4
cdr
-
(cdr consCell)
Get the last element of a cons cell.
Note: The weird names {car
, cdr
, cons
} are like that for historical reasons.
List is Made of Cons
Elisp list is built from cons. For example, this list:
(list 1 2 3)
it is identical to
(cons 1 (cons 2 (cons 3 nil)))
(equal (list "a") (cons "a" nil)) (equal (list "a" "b") (cons "a" (cons "b" nil))) (equal (list "a" "b" "c") (cons "a" (cons "b" (cons "c" nil))))