<< 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))))))))))))))))))
Footnote 9. states:
Since nested applications of car and cdr are cumbersome to write, Lisp dialects provide abbreviations for them -- for instance, (cadr <arg>) = (car (cdr <arg>)) The names of all such procedures start with c and end with r. Each a between them stands for a car operation and each d for a cdr operation, to be applied in the same order in which they appear in the name. The names car and cdr persist because simple combinations like cadr are pronounceable.
But, when I try (cadaddr (list 1 3 (list 5 7) 9)) It returns an error: ;Unbound variable: cadaddr
There is a limit of operations one can concatenate in cxxr format (only four). (Common Lisp HyperSpec: CAR, CDR & etc.)
Since (cdaddr (list 1 3 (list 5 7) 9)) returns (7), we can use (car (cdaddr (list 1 3 (list 5 7) 9))) to solve the first item.
I wrote a procedure to mimic the cxxr function. I don't like this implementation, but that was the way I found to make the function work (I had some problems trying to write a procedure to compare char values, or even evaluating a whole string of a&d's. Using a raw sequence of 0&1's was too cryptic).
(define a 0) (define d 1) (define (cr items . ad-seq) (define ops (reverse ad-seq)) (define (iter result oper) (if (null? oper) result (cond ((= (car oper) a) (iter (car result) (cdr oper))) ((= (car oper) d) (iter (cdr result) (cdr oper))) (else (error "Just cAr or cDr - - Char Not recognized" (car oper)))))) (iter items ops)) ;(1 3 (5 7) 9) (cr (list 1 3 (list 5 7) 9) a d a d d) ;Value: 7