与+和append一起使用的树型定义 [英] tree-fold defintion that works both with + and append
本文介绍了与+和append一起使用的树型定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
(define (tree-fold f tree)
(if (pair? tree)
(apply f (car tree) (map (lambda (t) (tree-fold f t)) (cdr tree)))
(f tree)))
<例如:(tree-fold +'(1(2 2)(2 2))
- > 9
然而,如果我想使用(tree-fold append'(1(2 2)(2 2)))
,
我必须在(car tree)
周围用 list
修改树形折叠
>,
将其分解为 +
。
是否有一些机制可用于树形折叠 code>定义,它可以同时处理
+
和追加
?
However if I want to use (tree-fold append '(1 (2 2)(2 2)))
,
I have to modify the tree-fold
with list
around (car tree)
,
which breaks it for +
.
Is there some mechanism that can be used in the tree-fold
definition that would make it work with both +
and append
?
推荐答案
这应该会起作用,并添加一个参数来初始化结果: $ b
This should work, adding one parameter to initialise the result:
(define (tree-fold f n sxp)
(let loop ((sxp sxp) (res n))
(cond
((null? sxp) res)
((pair? sxp) (loop (car sxp) (loop (cdr sxp) res)))
(else (f sxp res)))))
测试:
Testing:
> (tree-fold + 0 '(1 (2 2)(2 2)))
9
> (tree-fold cons '() '(1 (2 3)(4 5)))
'(1 2 3 4 5)
这篇关于与+和append一起使用的树型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文