Exercise 2.30
Define a procedure square-tree analogous to the square-list procedure of Exercise 2.21. That is, square-tree should behave as follows:
(square-tree
(list 1
(list 2 (list 3 4) 5)
(list 6 7)))
(1 (4 (9 16) 25) (36 49))
Define square-tree both directly (i.e., without using any higher-order procedures) and also by using map and recursion.
這個題目沒啥難度,直接仿照 scale-tree 函式,修改一下函式名就行了。
(define (square-tree tree)
(cond ((null? tree) nil)
((not (pair? tree)) (square tree))
(else (cons (square-tree (car tree))
(square-tree (cdr tree))))))
(define (square-tree-by-map tree)
(map (lambda (sub-tree)
(if (pair? sub-tree)
(square-tree-by-map sub-tree)
(square sub-tree)))
tree))
(define test (list 1
(list 2 (list 3 4) 5)
(list 6 7)))
(square-tree test)
(square-tree-by-map test)
; 執行結果
'(1 (4 (9 16) 25) (36 49))
'(1 (4 (9 16) 25) (36 49))