2.27 Exercise 2.27
There are a few subtle changes in deep-reverse that should be mentioned.
First, since all list structures need to be reversed, the base case now returns an atom and not a list. This means that instead of calling append, the general case needs to call cons.
Second, although the first base case is for whether the argument is not a pair, the case checking if the argument is a single-value list is still needed to produce correct list structures. The one item list case returns deep-reverse (car l), while the general case returns (cons (deep-reverse (cdr l)) (list (deep-reverse (car l)))) (where the second argument is still turned into a list).
The procedure is as follows:
(define (deep-reverse l) (cond ((not (pair? l)) l) ((null? (cdr l)) (deep-reverse (car l))) (else (cons (deep-reverse (cdr l)) (list (deep-reverse (car l)))))))
There need to be three cases here because even though (deep-reverse (cdr l)) will return nil if that’s what (cdr l) is, consing nil in front will create the wrong list structure. In other words,
> (define (deep-reverse l) (cond ((not (pair? l)) l) (else (cons (deep-reverse (cdr l)) (list (deep-reverse (car l))))))) > (deep-reverse x) (mcons (mcons (mcons '() (mcons 3)) (mcons 2)) (mcons 1))