Exercise2.28
Write a procedure fringe that takes as argument a tree (represented as a list) and returns a list whose elements are all the leaves of the tree arranged in left-to-right order. For example,
(define x (list (list 1 2) (list 3 4)))
(fringe x)
(1 2 3 4)
(fringe (list x x))
(1 2 3 4 1 2 3 4)
这道题我参考了 count-leaves 和 练习 2.27,其中比较难处理的可能是 tree 的第一部分,要注意这里的 result 应该是空的,其他地方逻辑跟 2.27 就没什么区别了。
(define (fringe tree)
(define (iter tree result)
(cond ((null? tree) result)
((not (pair? tree)) (cons tree result))
(else (append (iter (car tree) nil)
(iter (cdr tree) result)))))
(iter tree nil))
(define x (list (list 1 2) (list 3 4)))
(fringe x)
(fringe (list x x))
; 执行结果
'(1 2 3 4)
'(1 2 3 4 1 2 3 4)
标签:list,每日,fringe,tree,sicp,iter,2.28,result,define
From: https://www.cnblogs.com/think2times/p/18430943