SICP exercise 2.25
From Drewiki
Problem
Give combinations of cars and cdrs that will pick 7 from each of the following lists:
(1 3 (5 7) 9) ((7)) (1 (2 (3 (4 (5 (6 7))))))
Solution
For testing purposes, let's name each list:
(define list1 (list 1 3 (list 5 7) 9)) (define list2 (list (list 7))) (define list3 (list 1 (list 2 (list 3 (list 4 (list 5 (list 6 7)))))))
A simple method for constructing these car/cdr sequences is to find the 7 in the list, start with a car, and then work backwards towards the beginning of the list. For each integer you encounter, use a cdr. For the beginning of each list encountered, use a car until you reach the outer-most list.
For each combination given below, the output from the interpreter follows.
(car (cdr (car (cdr (cdr list1)))))
Output:
7
(car (car list2))
Output:
7
(car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr list3))))))))))))
Output:
7

