An easy way to understand the compound list functions
cadr/caddr/caddar/etc. is to recall that they are merely shorthand for a sequence of successive
car/cdr functions, e.g.:
_$ (cadddr '(1 2 3 4 5 6 7 8 9))
4Is equivalent to:
_$ (car (cdr (cdr (cdr '(1 2 3 4 5 6 7 8 9)))))
4Likewise:
_$ (caddar '((1 2 3 4 5) 6 7 8 9))
3Is equivalent to:
_$ (car (cdr (cdr (car '((1 2 3 4 5) 6 7 8 9)))))
3With that knowledge, all you need to remember is that
car accesses the first element of a list (
car =
content of the
address
register) and
cdr removes the first element of a list returning the tail of the list (
cdr =
content of the
decrement
register):
_$ (car '(1 2 3 4 5 6 7 8 9))
1
_$ (cdr '(1 2 3 4 5 6 7 8 9))
(2 3 4 5 6 7 8 9)And so when you see an expression such as:
(cddadr '(1 (2 3 4 5) 6 7 8 9))You can extract the list item by reading the sequence of '
a's and '
d's from right-to-left.
In the above example, reading from right to left, we have the sequence:
daddWhich means:
- Remove the first element and return the remainder of the list
- Extract the first element of the list
- Remove the next two elements and return the remainder of the list
Evaluating this in sequence yields:
(cddadr '(1 (2 3 4 5) 6 7 8 9))
(cddar '((2 3 4 5) 6 7 8 9))
(cddr '(2 3 4 5))
(cdr '(3 4 5))
(4 5)Which is indeed exactly what is returned when testing the expression at the console:
_$ (cddadr '(1 (2 3 4 5) 6 7 8 9))
(4 5)