Scheme, like all Lisp dialects, considers lists to be accessible only from the front (internally, they are represented as linked lists). Thus, Scheme provides a number of functions for accessing the first element of a list (the head) , the rest of the list not including the head (the tail) , inserting a new head, and so forth. We describe these here.
The car function, given a list, returns the head of that list. Note that the head of a list need not be an atom.
(car '(1 2 3)) 1Similarly, the cdr function returns the tail of a list. This return value is always a list.(car '((1 2) 3) (1 2)
(cdr '(1 2 3)) (2 3)Applying car or cdr to an empty list is an error.(cdr '((1 2) 3)) (3)
(cdr '(1 (2 3))) ((2 3))
(cdr '(1)) ()
The cons function is used for list construction; given an element and a list, it creates a new list identical to its list argument, but with the element added as the new head.
(cons '1 '(2 3)) (1 2 3)(cons '(1 2) '(3 4) ((1 2) 3 4)
The list function creates a list from a set of s-expressions. It takes a variable number of arguments, and merely formulates those arguments into a list.
(list '1 '2 '3) (1 2 3)(list '(1 2) '3) ((1 2) 3)
Several other useful list manipulations are provided as well: append , reverse , and length . Note that these are not primitives; they may easily be defined using the primitives described above.
The append function merely concatenates two lists.
(append '(1 2) '(3 4)) (1 2 3 4)
The reverse function reverses the order of elements in a list.
(reverse '(1 2 3)) (3 2 1)
The length function returns the length of the list in elements. Note that this does not include elements of any sublists; it merely counts the number of s-expressions that make up the list.
(length '(1 2 3)) 3(length '((1 2) 3)) 2