Search code examples
schemesicp

Understanding exercise 2.29 SICP - Binary modules


Just one minor thing, I don´t understand why procedure right-branch is like this:

(define (right-branch mobile)
   (car (cdr mobile)))

instead of:

(define (right-branch mobile)
   (cdr mobile))

As far as I know, car procedure return the first item in a list and cdr returns the "rest" of the list. So, if we have a mobile like this:

((1 2) (3 4))

the left branch is (1 2) and the right branch is (3 4). Is like this or am I missing something? Thanks.

And the same for procedure branch-structure.


Solution

  • The issue here is that (cdr '((1 2) (3 4))) is not '(3 4). Rather, it is '((3 4)).

    This is because the list is a list, containing three elements: two lists and the empty list (null). That means the list, expressed as pairs, actually looks like this:

    '((1 2) . ((3 4) . ()))
    

    Since cdr gets the right side of a pair, it returns the rest of the list, so even if only one element is left, it is wrapped in a containing list.