Cons
- In Lisp,
cons
is a core builtin function that links two values together by creating a memory object for the first value consisting of acar
(content of address register) andcdr
(content of decrement register):- the
car
contains the actual value of the list item - the
cdr
contains a pointer to acons
object containing the second value being linked - the
cons
object containing the second value likewise consists of acar
(the value) and acdr
(pointer to the nextcons
), ornil
, which terminates the singly linked list
- the
- Ordered pairs:
cons
can be notated(cons 1 2)
(creates objects for1
and2
and links them, terminating withnil
)cons
can alternatively be notated with a dot:(1 . 2)
- this is known as a “dotted pair” or a “cons pair”
- Lists:
-
The
list
function within Lisp usescons
internally(list 5 10 15)
…is the same as…
(cons 5 (cons 10 (cons 15 nil)))
-
this also means that
cons
can be used to “shift” (front-append) an element onto the front of a list
-
- Trees:
-
in truth, all singly linked lists are binary trees
-
thus, binary trees can be implemented with
cons
rather easily(cons (cons 1 2) (cons 3 4))
((1 . 2) . (3 . 4))
-