SICP Exercise 2.26
Question
Suppose we define x
and y
to be two lists:
(define x (list 1 2 3))
(define y (list 4 5 6))
What result is printed by the interpreter in response to evaluating each of the following expressions?
(append x y)
(cons x y)
(list x y)
Answer
(define x (list 1 2 3))
(define y (list 4 5 6))
(append x y)
(cons x y)
(list x y)
Results:
(1 2 3 4 5 6)
((1 2 3) 4 5 6)
((1 2 3) (4 5 6))
This highlights the difference between the three main ways in which lists
can be constructed in Scheme. Whereas append
is meant to take two lists
as an input and returns a flattened list with the elements of its two
parameters, cons
and list
keep the structure of some of their
parameters intact and return nested lists.
The difference between these two, then, is that cons
is meant to take as
its parameters a car
(single value) and a cdr
(a list), so it will keep
the structure of its first parameter intact. So then if the first
parameter is a list, the first element of the returned list will be that
same list, which now forms the car
.
list
simply takes its two input parameters and returns a new list
containing them, without modifying the two parameters in any way. So if
the two input values both happen to be lists, list
will return a list
containing these two lists, as seen in the output above.