乐正

Actions speak louder than words.

Sicp-ex2-27

问题

修改练习2.18中的reverse过程,得到一个deep-reverse过程。它以一个表为参数,返 回另一个表作为值,结果表中的元素反转过来,其中的子树也反转。例如:

1
2
3
4
5
6
7
8
9
10
(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))

解答

练习2.27 (ex2-27.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
;; Happy hacking Yuez - Emacs ♥ you!

(define (deep-reverse items)
  (define (reverse-iter remain-items result)
    (cond ((null? remain-items) result)
          ((pair? (car remain-items))
           (reverse-iter (cdr remain-items)
                         (cons (deep-reverse (car remain-items)) result)))
          (else (reverse-iter (cdr remain-items)
                              (cons (car remain-items) result)))))

  (reverse-iter items (list)))

测试

1
2
3
4
5
6
7
8
(define x (list (list 1 2) (list 3 4)))
;Value: x

(deep-reverse x)
;Value 68: ((4 3) (2 1))

(deep-reverse (list 1 3 (list 2 (list 3 4))))
;Value 69: (((4 3) 2) 3 1)

draft

« sicp-ex2-26 sicp-ex2-28 »

Comments