Although cons cells can be used to hold
ordered pairs of data, they are more commonly used to construct more complex compound data structures, notably
lists and
binary trees.
Ordered pairs For example, the Lisp expression constructs a cell holding 1 in its left half (the so-called field) and 2 in its right half (the field). In Lisp notation, the value looks like: (1 . 2) Note the dot between 1 and 2; this indicates that the S-expression is a "dotted pair" (a so-called "cons pair"), rather than a "list."
Lists In Lisp, lists are implemented on top of cons pairs. More specifically, any list structure in Lisp is either: • An empty list , which is a special object usually called . • A cons cell whose is the first element of the list and whose is a
list containing the rest of the elements. This forms the basis of a simple,
singly linked list structure whose contents can be manipulated with , , and . Note that is the only list that is not also a cons pair. As an example, consider a list whose elements are 1, 2, and 3. Such a list can be created in three steps: • Cons 3 onto , the empty list • Cons 2 onto the result • Cons 1 onto the result which is equivalent to the single expression: (cons 1 (cons 2 (cons 3 nil))) or its shorthand: (list 1 2 3) The resulting value is the list: (1 . (2 . (3 . nil))) i.e. *--*--*--nil | | | 1 2 3 which is generally abbreviated as: (1 2 3) Thus, can be used to add one element to the front of an existing linked list. For example, if
x is the list we defined above, then will produce the list: (5 1 2 3) Another useful list procedure is
append, which
concatenates two existing lists (i.e. combines two lists into a single list).
Trees Binary trees that only store data in their
leaves are also easily constructed with . For example, the code: (cons (cons 1 2) (cons 3 4)) results in the tree: ((1 . 2) . (3 . 4)) i.e. * / \ * * / \ / \ 1 2 3 4 Technically, the list (1 2 3) in the previous example is also a binary tree, one which happens to be particularly unbalanced. To see this, simply rearrange the diagram: *--*--*--nil | | | 1 2 3 to the following equivalent: * / \ 1 * / \ 2 * / \ 3 nil ==Use in conversation==