[英]trying to write Foldtree in Racket n-ary only know how to do write for binary tree
I am trying to write a fold command for a tree in DrRacket, only know how to write fo Binary tree.我正在尝试为 DrRacket 中的树编写折叠命令,只知道如何编写二叉树。 Have any suggestions how to do it?有什么建议吗? It should take a function f
such as +, - ect.它应该采用 function f
例如 +、- 等。 and fold all the given data, but not by flattening the tree.并折叠所有给定的数据,但不是通过展平树。
This is what I've come up with, so far:到目前为止,这是我想出的:
(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))))))
Thanks in advance!提前致谢!
Assuming the following definition,假设以下定义,
(define (nt-constr int children) (list int children))
(define (nt-val tree) (car tree))
(define (nt-children tree) (cadr tree))
You can follow the same pattern:您可以遵循相同的模式:
(define (nt-fold f int tree)
(if (null? tree) int
(f (nt-val tree)
(... fold the children ...))))
Now, you can fold all the children and get a list of their respective "folded values" using map
,现在,您可以使用map
折叠所有孩子并获取它们各自的“折叠值”列表,
(map (lambda (t) (nt-fold f t)) (nt-children tree))
and you can apply the function to this list using apply
:您可以使用apply
将 function 应用于此列表:
(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))))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.