Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 views
in Technique[技术] by (71.8m points)

lisp - 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...