<< Previous exercise (2.24) | Index | Next exercise (2.26) >>

(car (cdr (car (cdr (cdr '(1 3 (5 7) 9)))))) (car (car '((7)))) (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr '(1 (2 (3 (4 (5 (6 7))))))))))))))))))

to leave a list, you would car. to move up the list, you would cdr. working from the inside, starting from 7. you would need to leave the list (7 is in a list by itself), then move up the list to six with cdr, together they make one cadr. then you are at the same position again with (6 7) instead of the 7. so you would need to leave the (6 7) list then move up a position to 5.

so it is just a repetition of cadr for eace 'wrap'.

(define third '(1 (2 (3 (4 (5 (6 7))))))) (display (cadr (cadr (cadr (cadr (cadr (cadr third)))))))

2.25 seems pretty easy, but it gets rather hairy.

a.

The final car (on the left) is needed to pull the 7 from the (cons 7 nil) list.

To build the cons equivalent of the original:

Step 1: replace (list 5 7) with x:

Step 2: replace x with cons equivalent:

b.

c.

I thought the answer was just:

but no.

Building up from the inside out:

is by definition

Replace (list 6 7) with x for a second to see this is just

Resubstitute the expanded expression for x:

So, any time we add another "wrapping list" we'll need to add the underlined portions, replacing z with the appropriate value.

Therefore,

is equivalent to

Which is pretty ugly (actually, I'll call this "ugly" in the explanation below).

Anyway, to retrieve the 7, we need to do the following:

Which is also frightful.

Explanation:

The innermost cdr gives the section after the number 1 in ugly, or "(cons (cons 2 ...".

The next car gives "(cons 2 (cons ...").

The next cdr gives "(cons (cons 3 ...".

The next car gives "(cons 3 ...", etc.

Eventually, we get to (cons 7 nil), which is the final car.

Yuck.