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 (lambda (t) (nt-fold f t)) (nt-children tree))
and you can apply the function to this list using 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))))))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…