Question: please help! I don't really understand OCaml! In hw3.ml , Copy this line to the start of the file: type 'a tree = Leaf |
please help! I don't really understand OCaml!
In hw3.ml,
Copy this line to the start of the file: type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree
Write a function fold_tree of type 'b -> ('a -> 'b -> 'b -> 'b) -> 'a tree -> 'b that folds a tree like how List.fold_right folds a list (see Section 4.4Links to an external site.):
fold_tree init f Leaf is init
fold_tree init f (Node (x, left, right)) is equal to f x (fold_tree init f left) (fold_tree init f right)
For example,
fold_tree 0 (fun x left right -> x + left + right) t will sum up all the numbers in t.
fold_tree 1 (fun _ left right -> left + right) t will count the number of leaves in t.
[NEWLY ADDED HINT] Make sure you understand the above two examples of fold_tree before moving on. One of them is summing up numbers and the other is counting leaves. Why? How do they work? Before solving for_all_tree, it is wise to study those two examples first. It might also be helpful to review how sum_list was defined in terms of fold_right in the lecture.
Use fold_tree to define a function for_all_tree of type ('a -> bool) -> 'a tree -> bool where for_all_tree p t checks whether for every data x in the tree t, p x is true. It is similar to exists_tree but works as a universal quantifier instead of an existential quantifier. For example,
for_all_tree (fun x -> x > 0) (Node (100, Leaf, Leaf)) is true because 100 > 0.
for_all_tree (fun x -> x mod 2 = 0) Leaf is true because there are no data in the tree.
for_all_tree (function Some _ -> true | None -> false) (Node (Some 1, Node (None, Leaf, Leaf), Leaf)) is false because the functional argument is checking whether every datum is Some _ but there is one None in the tree.
Thank you for your help!!!
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
