treelispracketfoldarity

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. Have any suggestions how to do it? It should take a function f such as +, - ect. 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!


Solution

  • 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))))))