Scheme programs are lists, but lists can be data too. Scheme provides syntactic support for lists, and a variety of standard functions for manipulating them. The following "quoted list" is Scheme syntax for the list containing 1, 2, 3, and 4:
'(1 2 3 4) ; Unlike the list (1 2 3 4), we do not evaluate this list ; as a special form or function call. The single quote ; in Scheme means: "This is data; do not evaluate it." '(define a 7) ; The list containing define, a, and 7. This list's parts ; are not evaluated, and nothing is bound to the symbol a.
The special list nil is represented by ()
. Below
are pictures of the two lists constructed above. Each bipartite
box is called a "list cell" or a "cons cell".
()
is implemented?()
and '()
?An alternative way of defining lists of data is to use the
function list
. This is not exactly equivalent,
because it does not prevent the elements in the list from being
evaluated:
'(1 2 (+ 1 2)) ; Evaluates to the list '(1 2 (+ 1 2)) (list 1 2 (+ 1 2)) ; Evaluates to the list '(1 2 3) ; Can you draw pictures of these two lists?
A third way to construct lists is using the cons
function, which takes two arguments and constructs a single cons
cell:
(cons 1 (cons 2 (cons 3 (cons 4 ())))) ; Equivalent to '(1 2 3 4) ; Cons doesn't force you to construct well-formed ("proper") lists. ; It is only by convention that the first element carries the "payload" ; while the second element points to the "tail" (rest of the list) (cons 1 2) (cons (cons 1 2) (cons 3 ()))