Second sentence of Section 2.2.2 (Hierarchical Structures) of SICP: the authors say that ((1 2) 3 4)
(a list of three elements) can be constructed by (cons (list 1 2) (list 3 4))
.
I think (wrongly so, of course) that it will construct ((1 2) (3 4))
(two elements) instead because:
3
and 4
will be enclosed in a nested list
not in the top-level cons
, andcons
constructs a pair of items, and pair means 2 elements not 3.What am I failing to understand here?
A list is a chain of pairs, ending with a pair whose cdr
is the empty list.
(list 3 4)
is two pairs, equivalent to
(cons 3 (cons 4 '()))
So (cons (list 1 2) (list 3 4))
is 3 pairs, equivalent to
(cons (list 1 2) (cons 3 (cons 4 '())))
In general, if you have a list old-list
, you can create a new list with a new element on the front with:
(cons new-element old-list)
You would get what you expected if you wrote
(list (list 1 2) (list 3 4))