Emacs Lisp: 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 First/Last 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 "a" "b" "c")
it is identical to
(cons "a" (cons "b" (cons "c" nil)))
Proper List
Lisp Data Structure
List
- Cons Pair
- Quote and Dot Notation
- Proper List
- List
- Create List
- List, Get Elements
- Modify List
- Check Element Exist in List
- Remove Elements in List
- Backquote Reader Macro