sicp每日一题[2.31]

Exercise 2.31

Abstract your answer to Exercise 2.30 to produce a procedure $tree-map$ with the property that $square-tree$ could be defined as

(define (square-tree tree) (tree-map square tree))

这道题跟上面一道的 map 实现几乎一模一样,我还以为我理解错题目了,上网搜了一下,发现别人也是这么写的,那就这样吧。

(define (tree-map f tree)
  (map (lambda (sub-tree)
         (if (pair? sub-tree)
             (tree-map f sub-tree)
             (f sub-tree)))
       tree))

(define (square-tree tree) (tree-map square tree))


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

; 执行结果
'(1 (4 (9 16) 25) (36 49))
posted @ 2024-09-28 08:37  再思即可  阅读(2)  评论(0编辑  收藏  举报