Question: Language: R5RS Racket Write a function called treeReduce for trees that is analogous to the given reduce function. This function should take an operator, an

Language: R5RS Racket

  1. Write a function called treeReduce for trees that is analogous to the given reduce function. This function should take an operator, an initial value, and a tree as arguments and return the result of combining all nodes of the tree using the given operator. For simplicity you may assume only commutative operators are supplied. E.g.:
    1. (treeReduce + 0 '(1 (2 3) ((4 5) 6 (7) ((8 (9)) 10))) 55
 (define (reduce operator initial sequence)
 (if (null? sequence)
 initial
 (operator (car sequence) 
 (reduce operator initial (cdr sequence)))))
 
  1. Write a function height that takes as argument an arbitrarily deeply nested list (i.e. a tree) and returns the maximum depth of any item in any of its sublists; the depth of an object in a list is the number of cars that can be applied to it, not necessarily in a row... (You may wish to use the built-in max function for this).

E.g.:

(height 'a) 0

(height '(a)) 1

(height '(a (b) c)) 2

(height '(((((a(((b))))))))) 8

  1. Write a function flattenTree that takes a tree as an argument and returns a list of the leaf values of the tree. E.g.:

(flattenTree '(1 (2 3) ((4 5 6 (7)))(((8 (9)))))) (1 2 3 4 5 6 7 8 9)

  1. Write a function (treeMerge T1 T2) that takes two trees as arguments and merges them according to the following rules:
  • Merging two trees is done by recursing through their structure and merging their subtrees.
    • The root of T1 is merged with the root of T2
    • The first child is merged with the first child
    • Second with second... etc, etc, etc, ...
  • Merging two leaf nodes is done by multiplying their values (you may assume they are numbers).
  • Merging a leaf node with a subtree is done by scaling the subtree by the value of the leaf.
  • Merging a subtree with an empty tree, is simply the non-empty subtree.

E.g.:

Language: R5RS Racket Write a function called treeReduce for trees that is

(2(3) (2 (23) (45567))) (12) (18) (28) (40) 8)(6) (4 2 ) (567) (10 (86) (42) (1218) (2840 (567) (5 (43) (21) 6(78) (2(3) (2 (23) (45567))) (12) (18) (28) (40) 8)(6) (4 2 ) (567) (10 (86) (42) (1218) (2840 (567) (5 (43) (21) 6(78)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!