Contents    Page-10    Prev    Next    Page+10    Index   

Constructing a List

A list can be built up by linking new elements onto the front. The function (cons item list ) makes a new list element or cons cell pointing to item and adds it to the front of list:


(cons 'a nil)              ->  (a)
(cons 'a '())              ->  (a)
(cons 'a (list))           ->  (a)
(cons 'a '(b c))           ->  (a b c)

An easy way to think of (cons x y) is that it makes a new cons box whose first is x and whose rest is y, or that cons adds a new item to the front of an existing list.

Note that there is structure sharing between the result of cons and the list that is the second argument of cons.


(def x '(a b c))
(def y (cons 'd x))
>x
(a b c)
>y
(d a b c)  ; x and y share (a b c)