; ======================================================================
;
; Structure and Interpretation of Computer Programs
; (trial answer to excercises)
;
; 计算机程序的构造和解释(习题试解)
;
; created: code17 07/28/05
; modified:
; (保持内容完整不变前提下,可以任意转载)
; ======================================================================
;; SICP No.2.31
;; 基本版本
(define (tree-map f tree)
(cond ((null? tree) ())
((not (pair? tree)) (f tree))
(else (cons (tree-map f (car tree))
(tree-map f (cdr tree))))))
;; Map版本
(define (tree-map f tree)
(map (lambda (sub-tree)
(if (pair? sub-tree)
(tree-map f sub-tree)
(f sub-tree)))
tree))
;; Test-it:
;; Welcome to MzScheme version 209, Copyright (c) 2004 PLT Scheme, Inc.
;; > (define (square-tree tree) (tree-map sqr tree))
;; > tree-1
;; (1 (2 (3 4) 5) (6 7))
;; > (square-tree tree-1)
;; (1 (4 (9 16) 25) (36 49))