SICP Exercise 2.25
Question
Give combinations of car
s and cdr
s that will pick 7
from each of the
following lists:
(1 3 (5 7) 9)
((7))
(1 (2 (3 (4 (5 (6 7))))))
Answer
You can either do this using only car
and cdr
or with some of the
helper functions offered by Scheme, such as cadadr
and the like. But
keep in mind these only exist until up to four letters between c
and r
,
so there is no such thing as cadaddr
or cadadadadadadr
.
(define l1 (list 1 3 (list 5 7) 9))
(define l2 (list (list 7)))
(define l3 (list 1 (list 2 (list 3 (list 4 (list 5 (list 6 7)))))))
(car (cdr (car (cdr (cdr l1)))))
; or
(car (cdaddr l1))
(car (car l2))
; or
(caar l2)
(car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr l3))))))))))))
; or
(cadadr (cadadr (cadadr l3)))
Here are the results of the above:
7
7
7
7
7
7