乐正

Actions speak louder than words.

Sicp-ex2-30

问题

请定义一个与练习2.21中square-list过程类似的square-tree过程。也就是说,它应该 具有下面的行为:

1
2
3
4
5
6
(square-tree
  (list 1
        (list 2 (list 3 ) 5)
        (list 6 7)))

(1 (4 (9 16) 25) (36 49))

请以两种方式定义square-tree,直接定义(即不使用任何高阶函数),以及使用map 和递归定义。

解答

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

(define (square-tree-nomap tree)
  (cond ((null? tree) (list))
        ((not (pair? tree)) (square tree))
        (else (cons (square-tree-nomap (car tree))
                    (square-tree-nomap (cdr tree))))))

(define (square-tree-map tree)
  (map (lambda (sub-tree)
         (if (not (pair? sub-tree))
             (square sub-tree)
             (square-tree-map sub-tree)))
       tree))

测试

1
2
3
4
5
6
7
8
9
10
11
(square-tree-nomap
 (list 1
       (list 2 (list 3 4) 5)
       (list 6 7)))
;Value 14: (1 (4 (9 16) 25) (36 49))

(square-tree-map
 (list 1
       (list 2 (list 3 4) 5)
       (list 6 7)))
;Value 15: (1 (4 (9 16) 25) (36 49))

draft

« sicp-ex2-29 sicp-ex2-31 »

Comments