试图在 Racket n-ary 中编写 Foldtree 只知道如何为二叉树编写

trying to write Foldtree in Racket n-ary only know how to do write for binary tree

我正在尝试在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))))))