Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fold_tree in OCaml

As You may know, there are higher order functions in OCaml, such as fold_left, fold_right, filter etc.

On my course in functional programming had been introduced function named fold_tree, which is something like fold_left/right, not on lists, but on (binary) trees. It looks like this:

 let rec fold_tree f a t = 
  match t with
    Leaf -> a |
    Node (l, x, r) -> f x (fold_tree f a l) (fold_tree f a r);;

Where tree is defined as:

type 'a tree = 
  Node of 'a tree * 'a * 'a tree | 
  Leaf;;

OK, here's my question: how does the fold_tree function work? Could you give me some examples and explain in human language?

like image 201
equrts Avatar asked Nov 15 '10 22:11

equrts


1 Answers

Here's a style suggestion, put the bars on the beginning of the line. It makes it clearer where a case begins. For consistency, the first bar is optional but recommended.

type 'a tree = 
  | Node of 'a tree * 'a * 'a tree
  | Leaf;;

let rec fold_tree f a t = 
    match t with
      | Leaf -> a
      | Node (l, x, r) -> f x (fold_tree f a l) (fold_tree f a r);;

As for how it works, consider the following tree:

let t = Node(Leaf, 5, Node(Leaf, 2, Leaf));;

With the type int tree.

Visually, t looks like this:

   5
  / \
 ()  2
    / \
   () ()

And calling fold_tree, we'd need a function to combine the values. Based on the usage in the Node case, f takes 3 arguments, all the same type of the tree's and returns the same. We'll do this:

let f x l r = x + l + r;; (* add all together *)
fold_tree f 1 t;;

It would help to understand what happens in each case. For any Leaf, a is returned. For any Node, it combines the stored value and the result of folding the left and right subtrees. In this case, we're just adding the numbers where each leaf counts as one. The result on the folding of this tree is 10.

like image 194
Jeff Mercado Avatar answered Sep 28 '22 07:09

Jeff Mercado