A cons cell, also known as a dotted pair (because of its printed representation), is simply a pair of two objects. A cons cell is created by the function cons
, and elements in the pair are extracted using the functions car
and cdr
.
(cons "a" 4)
For instance, this returns a pair whose first element (which can be extracted with car
) is "a"
, and whose second element (which can be extracted with cdr
), is 4
.
(car (cons "a" 4))
;;=> "a"
(cdr (cons "a" 4))
;;=> 3
Cons cells can be printed in dotted pair notation:
(cons 1 2)
;;=> (1 . 2)
Cons cells can also be read in dotted pair notation, so that
(car '(x . 5))
;;=> x
(cdr '(x . 5))
;;=> 5
(The printed form of cons cells can be a bit more complicated, too. For more about that, see the example about cons cells as lists.)
That's it; cons cells are just pairs of elements created by the function cons
, and the elements can be extracted with car
and cdr
. Because of their simplicity, cons cells can be a useful building block for more complex data structures.