Search code examples
listnestedschemesicp

How is this the correct representation of the given nested structure [SICP]? What am I missing?


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:

  1. 3 and 4 will be enclosed in a nested list not in the top-level cons, and
  2. cons constructs a pair of items, and pair means 2 elements not 3.

What am I failing to understand here?


Solution

  • 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))