I am a beginner at Racket and I got this question:
- define a structure,
node, which has these fields:value,left,middle,right. This structure represents nodes in a tree structure.
These fields contain the value stored in the node, the left subtree, the middle subtree, and the right subtree respectively. If a subtree does not exist, then the corresponding field should contain anemptyNodeas described below.- define a structure,
emptyNode, to specify an empty node in the tree.- Write a function,
treeFold, which takes a function,f, an initial value,initial, and a tree structure,tree, as parameters. It should then produce a single value which is the result of usingfto fold the values in the tree (usingleft,middle, andrightsubtrees in that order). Note thatfis a function that takes two parameters. The first parameter is a value from the tree and the second is the partially accumulated result.
the function call should be :
(treeFold (lambda (a acc) (+ a acc)) 15 tree)
tree:
(node 7 (node 5 (emptyNode) (emptyNode) (emptyNode))
(node 20 (emptyNode) (emptyNode) (emptyNode))
(emptyNode))
the output : 47
this is what I did so far:
(struct node (value left middle right) #:transparent)
(struct emptyNode () #:transparent)
(define tree
(node 7
(node 5 (emptyNode) (emptyNode) (emptyNode))
(node 20 (emptyNode) (emptyNode) (emptyNode))
(emptyNode)))
(define (treeFold f initial tree)
(if (emptyNode? tree)
(emptyNode)
(node (f initial (node-value tree))
(node-left tree)
(node-middle tree)
(node-right tree))))
How can I get the total of the whole leaves?
any ideas or help, thanks
edit: so, based on the answer and discussion in its comments I got a new function but there is still a mistake and I could not find it. here it is:
(define (treeFold f initial tree)
(cond
[(emptyNode? tree)
(f initial 0)]
[else (f (node-value tree)
(f (treeFold f
(treeFold f
(treeFold f initial
(node-left tree))
(node-middle tree))
(node-right tree))))]))
could you please tell me how to fix it? thank you.
edit: final code
(define (treeFold f initial tree)
(cond
[(emptyNode? tree) (f initial 0)]
[else (f (node-value tree)
(treeFold f
(treeFold f
(treeFold f initial
(node-left tree))
(node-middle tree))
(node-right tree)))]))
it works as I expected
collectAllStringsInWholeTreewon't work under it. there's no need to combineinitialwith0on the empty node. why0? what if it's strings we're dealing with? justinitialis enough, there. except for that, well done. :) it defines a post-order traversal of a tree, whereas my answer suggests a pre-order one. I guess both are OK as it is not specified in the requirements. but since it is named "initial", I'd expect pre-order be the intended one. otherwise it'd be named "final" or something. - Will Ness+it doesn't matter, but what if it were-? or strings withstring-append? then the results for pre- and post-order folding would be different, in general. i.e.(treeFold - 100 tree)should return68, I think. - Will Ness