weima learns to program

my attempt to do the exercises in sicp.

Wednesday, July 16, 2008

sicp exercise 2.27

;  Exercise 2.27. Modify your reverse procedure of exercise 2.18 to produce a deep-reverse
;  procedure that takes a list as argument and returns as its value the list with its elements
;  reversed and with all sublists deep-reversed as well. For example,
;  (define x (list (list 1 2) (list 3 4)))
;  x
;  ((1 2) (3 4))
;  (reverse x)
;  ((3 4) (1 2))
;  (deep-reverse x)
;  ((4 3) (2 1))

(define reverse1 (lambda (items)
(define reverse1-impl (lambda (items result)
(cond ((null? items) result)
(else (reverse1-impl (cdr items) (cons (car items) result))))))
(reverse1-impl items (list))))

(define deep-reverse (lambda (items)
(define deep-reverse-impl (lambda (items result)
(cond ((null? items) result)
((pair? (car items)) (deep-reverse-impl (cdr items) (cons (deep-reverse-impl (car items) (list)) result)))
(else (deep-reverse-impl (cdr items) (cons (car items) result))))))
(deep-reverse-impl items (list))))

(define x (list 1 2 3 4))
(define y (list 1 2 (list 4 5)))
(define z (list (list 1 2) (list 3 4)))

(display x) (newline)
(display (reverse1 x )) (newline)
(display (deep-reverse x )) (newline)

(display y) (newline)
(display (reverse1 y )) (newline)
(display (deep-reverse y )) (newline)

(display z) (newline)
(display (reverse1 z )) (newline)
(display (deep-reverse z )) (newline)