问题描述
我正在尝试在 DrRacket 中为树编写折叠命令,只知道如何编写二叉树。
有什么建议怎么做吗?
它应该采用函数 f
,例如 +、- 等。并折叠所有给定的数据,但不是通过展平树。
到目前为止,这是我想出的:
(define (bt-constr int left right) (list int left right))
(define (bt-val tree) (car tree))
(define (bt-left tree) (cadr tree))
(define (bt-right tree) (caddr tree))
(define (bt-fold f int tree)
(if (null? tree) int
(f (bt-val tree) (f (bt-fold f int (bt-left tree)) (bt-fold f int (bt-right tree))))))
提前致谢!
解决方法
假设下面的定义,
(define (nt-constr int children) (list int children))
(define (nt-val tree) (car tree))
(define (nt-children tree) (cadr tree))
可以遵循相同的模式:
(define (nt-fold f int tree)
(if (null? tree) int
(f (nt-val tree)
(... fold the children ...))))
现在,可以折叠所有的孩子,得到使用其各自的“折叠值”的列表map
,
(map (lambda (t) (nt-fold f t)) (nt-children tree))
和可以使用应用功能到该列表apply
:
(define (nt-fold f int tree)
(if (null? tree) int
(f (nt-val tree)
(apply f (map (lambda (t) (nt-fold f int t)) (nt-children tree))))))