2.2.1 Representing Sequences
- View
- Revisions

One of the useful structures we can build with pairs is a sequence — an ordered collection of data objects. There are, of course, many ways to represent sequences in terms of pairs. One particularly straightforward representation is illustrated in figure 2.4, where the sequence 1, 2, 3, 4 is represented as a chain of pairs. The car
of each pair is the corresponding item in the chain, and the cdr
of the pair is the next pair in the chain. The cdr
of the final pair signals the end of the sequence by pointing to a distinguished value that is not a pair, represented in box-and-pointer diagrams as a diagonal line and in programs as the value of the variable nil
. The entire sequence is constructed by nested cons
operations:
(cons 1
(cons 2
(cons 3
(cons 4 nil))))
Such a sequence of pairs, formed by nested cons
es, is called a list, and Scheme provides a primitive called list
to help in constructing lists.[8] The above sequence could be produced by (list 1 2 3 4)
. In general,
(list <a1> <a2> … <an>)
is equivalent to
(cons <a1> (cons <a2> (cons … (cons <an> nil) …)))
Lisp systems conventionally print lists by printing the sequence of elements, enclosed in parentheses. Thus, the data object in figure 2.4 is printed as (1 2 3 4)
:
(define one-through-four (list 1 2 3 4))
one-through-four
(1 2 3 4)
Be careful not to confuse the expression (list 1 2 3 4)
with the list (1 2 3 4)
, which is the result obtained when the expression is evaluated. Attempting to evaluate the expression (1 2 3 4)
will signal an error when the interpreter tries to apply the procedure 1
to arguments 2
, 3
, and 4
.
We can think of car
as selecting the first item in the list, and of cdr
as selecting the sublist consisting of all but the first item. Nested applications of car
and cdr
can be used to extract the second, third, and subsequent items in the list.[9] The constructor cons
makes a list like the original one, but with an additional item at the beginning.
(car one-through-four)
1(cdr one-through-four)
(2 3 4)(car (cdr one-through-four))
2(cons 10 one-through-four)
(10 1 2 3 4)(cons 5 one-through-four)
(5 1 2 3 4)
The value of nil
, used to terminate the chain of pairs, can be thought of as a sequence of no elements, the empty list. The word nil is a contraction of the Latin word nihil, which means “nothing.”[10]
List operations
The use of pairs to represent sequences of elements as lists is accompanied by conventional programming techniques for manipulating lists by successively “cdr
ing down” the lists. For example, the procedure list-ref
takes as arguments a list and a number n and returns the nth item of the list. It is customary to number the elements of the list beginning with 0. The method for computing list-ref
is the following:
- For n = 0,
list-ref
should return thecar
of the list. - Otherwise,
list-ref
should return the (n - 1)st item of thecdr
of the list.
(define (list-ref items n)
(if (= n 0)
(car items)
(list-ref (cdr items) (- n 1))))
(define squares (list 1 4 9 16 25))
(list-ref squares 3)
16
Often we cdr
down the whole list. To aid in this, Scheme includes a primitive predicate null?
, which tests whether its argument is the empty list. The procedure length
, which returns the number of items in a list, illustrates this typical pattern of use:
(define (length items)
(if (null? items)
0
(+ 1 (length (cdr items)))))
(define odds (list 1 3 5 7))
(length odds)
4
The length
procedure implements a simple recursive plan. The reduction step is:
- The
length
of any list is 1 plus thelength
of thecdr
of the list.
This is applied successively until we reach the base case:
- The
length
of the empty list is 0.
We could also compute length
in an iterative style:
(define (length items)
(define (length-iter a count)
(if (null? a)
count
(length-iter (cdr a) (+ 1 count))))
(length-iter items 0))
Another conventional programming technique is to “cons
up” an answer list while cdr
ing down a list, as in the procedure append
, which takes two lists as arguments and combines their elements to make a new list:
(append squares odds)
(1 4 9 16 25 1 3 5 7)(append odds squares)
(1 3 5 7 1 4 9 16 25)
Append
is also implemented using a recursive plan. To append
lists list1
and list2
, do the following:
- If
list1
is the empty list, then the result is justlist2
. - Otherwise,
append
thecdr
oflist1
andlist2
, andcons
thecar
oflist1
onto the result:
(define (append list1 list2)
(if (null? list1)
list2
(cons (car list1) (append (cdr list1) list2))))
Since nested applications of car
and cdr
are cumbersome to write, Lisp dialects provide abbreviations for them — for instance,
The names of all such procedures start with c
and end with r
. Each a
between them stands for a car
operation and each d
for a cdr
operation, to be applied in the same order in which they appear in the name. The names car
and cdr
persist because simple combinations like cadr
are pronounceable. [back]
nil
be an ordinary name? Should the value of nil
be a symbol? Should it be a list? Should it be a pair? In Scheme, nil
is an ordinary name, which we use in this section as a variable whose value is the end-of-list marker (just as true
is an ordinary variable that has a true value). Other dialects of Lisp, including Common Lisp, treat nil
as a special symbol. The authors of this book, who have endured too many language standardization brawls, would like to avoid the entire issue. Once we have introduced quotation in section 2.3, we will denote the empty list as '()
and dispense with the variable nil
entirely. [back]
Exercises
Mapping over lists
One extremely useful operation is to apply some transformation to each element in a list and generate the list of results. For instance, the following procedure scales each number in a list by a given factor:
(define (scale-list items factor)
(if (null? items)
nil
(cons (* (car items) factor)
(scale-list (cdr items) factor))))
(scale-list (list 1 2 3 4 5) 10)
(10 20 30 40 50)
We can abstract this general idea and capture it as a common pattern expressed as a higher-order procedure, just as in section 1.3. The higher-order procedure here is called map
. Map
takes as arguments a procedure of one argument and a list, and returns a list of the results produced by applying the procedure to each element in the list:[12]
(define (map proc items)
(if (null? items)
nil
(cons (proc (car items))
(map proc (cdr items)))))
(map abs (list -10 2.5 -11.6 17))
(10 2.5 11.6 17)
(map (lambda (x) (* x x))
(list 1 2 3 4))
(1 4 9 16)
Now we can give a new definition of scale-list
in terms of map
:
(define (scale-list items factor)
(map (lambda (x) (* x factor))
items))
Map
is an important construct, not only because it captures a common pattern, but because it establishes a higher level of abstraction in dealing with lists. In the original definition of scale-list
, the recursive structure of the program draws attention to the element-by-element processing of the list. Defining scale-list
in terms of map
suppresses that level of detail and emphasizes that scaling transforms a list of elements to a list of results. The difference between the two definitions is not that the computer is performing a different process (it isn’t) but that we think about the process differently. In effect, map
helps establish an abstraction barrier that isolates the implementation of procedures that transform lists from the details of how the elements of the list are extracted and combined. Like the barriers shown in figure 2.1, this abstraction gives us the flexibility to change the low-level details of how sequences are implemented, while preserving the conceptual framework of operations that transform sequences to sequences. Section 2.2.3 expands on this use of sequences as a framework for organizing programs.
Scheme standardly provides a map
procedure that is more general than the one described here. This more general map
takes a procedure of n arguments, together with n lists, and applies the procedure to all the first elements of the lists, all the second elements of the lists, and so on, returning a list of the results. For example:
(map + (list 1 2 3) (list 40 50 60) (list 700 800 900))
(741 852 963)(map (lambda (x y) (+ x (* 2 y))) (list 1 2 3) (list 4 5 6))
(9 12 15)
Exercises
Comments
Post new comment