SICP solution exercise 2.27

Solution for exercise 2.27 of SICP:

;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))

(define (deep-reverse a)
  (cond ((null? a) a)
        ((not (pair? a)) a)
        (else (append (deep-reverse (cdr a)) (list (deep-reverse (car a)))))))

(deep-reverse x)
;((4 3) (2 1))

(display '--------tests--------)
(newline)

; tests
(define y (list 1 2 3))
y
(reverse y)
(deep-reverse y)

(define z (list 1 (list 2 3)))
z
(reverse z)
(deep-reverse z)

(define p (list 1 2 (list 3 4 (list 5 6))))
p
(reverse p)
(deep-reverse p)


(define q (list 1 2 (list 3 4 (list 5 6)) (list 7 8 ) 9 10))
q
(reverse q)
(deep-reverse q)

(define c (list 1 2 3))
(define d (list 4 5 6))
(define e (list c d))
e
(reverse e)
(deep-reverse e)

This entry was posted in SICP and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>