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 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 x (cons 3 4)) ;; get first element (car x) ; 3 ;; get last element (cdr x) ; 4
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
A cons structure whose last tail is nil, is called Proper List, or nil-terminated list.
;; proper lists (cons nil nil) (cons 3 nil) (cons 3 (cons 3 nil)) (cons 3 (cons 3 (cons 3 nil))) (cons 3 (cons 3 (cons 3 (cons 3 nil)))) ;; also proper lists. right-most tail is nil (cons (cons 3 4) nil) (cons (cons 3 4) (cons 3 nil)) (cons (cons (cons 3 4) 4) nil)
;; all true (proper-list-p (cons nil nil)) (proper-list-p (cons 3 nil)) (proper-list-p (cons 3 (cons 3 nil))) (proper-list-p (cons 3 (cons 3 (cons 3 nil)))) (proper-list-p (cons 3 (cons 3 (cons 3 (cons 3 nil))))) ;; true (proper-list-p (cons (cons 3 4) nil))
(equal (list "a") (cons "a" nil)) ;; t (equal (list "a" "b") (cons "a" (cons "b" nil))) ;; t (equal (list "a" "b" "c") (cons "a" (cons "b" (cons "c" nil)))) ;; t
Improper List
A cons that's not proper list is called Improper List .
;; improper list (cons nil 3) (cons (cons 3 nil) 3)
;; improper list ;; all false ;; tail is not nil (proper-list-p (cons nil 3)) ;; tail is not nil (proper-list-p (cons (cons 3 nil) 3))
Proper List vs Improper List
- Any cons structure, is a list.
- Proper list and improper list are both lists.
Most list functions, assume you have a proper list. That is, they assume you have a nil as the last tail in the cons structure. Practically all functions that return a list, return a proper list. This is critical to know.
Improper list is rarely used.
Dot Notation '(a . b)
(cons a b)
has a syntax shortcut
'(a . b)
(equal (cons 3 4) '(3 . 4)) ; t (equal (cons 'a 'b) '(a . b)) ; t