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

问题描述

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...