Exercise 1.4.9
Even More CAR and CDR
Because car
and cdr
are purely functional, and return their target value, it's possible to chain them in order to look into nested structures.
* (cons (cons 1 2) 3)
((1 . 2) . 3)
* (car (car (cons (cons 1 2) 3)))
1
This also applies to deeply nested lists.
* (defparameter *tree* (list 1 (list 2 3) (list 4 (list (list 5) 6 7 8))))
*tree*
* *tree*
(1 (2 3) (4 ((5) 6 7 8)))
* (car (cdr (car (cdr *tree*))))
3
This is common enough that Lisp supports shorthand for such tree selections.
* (car *tree*)
1
* (cadr *tree*)
(2 3)
* (cadadr *tree*)
3
* (cddr *tree*)
((4 ((5) 6 7 8)))
* (cdddr *tree*)
NIL
They're actual functions though. Not a reader syntax based on the number of a
s and d
s between the c
and r
. So, for instance:
* (caddadddaaar *tree*)
The function COMMON-LISP-USER::CADDADDDAAAR is undefined.
[Condition of type UNDEFINED-FUNCTION]