0

Suppose we defined a tree of integers :

type inttree = Int of int | Node of inttree * inttree ;;

is there any possible way to find the sum of the elements of that tree ?

user22323
  • 189
  • 7
  • 1
    Why not just to write a function that iterates over all nodes using DFS or something? – Pavel Zaichenkov Sep 15 '13 at 14:54
  • What is DFS ? Can you provide an example for it - i'm just new to the functional approach and due to the lack of resources and time , i'm escaping theory and taking the coding-a-lot approach - . and thanks . – user22323 Sep 15 '13 at 14:59
  • 2
    When you need to iterate over all nodes in the graph (tree is also a graph) and to do *something* with each node (in your case you need to sum all values of nodes), [Depth-first search](http://en.wikipedia.org/wiki/Depth-first_search) or [Breadth-first search](http://en.wikipedia.org/wiki/Breadth-first_search) is normally used. The difference is in the traversal order, what is not important in your case. So the easiest way to do it is just to write a 4-line recursive function, where you either read and accumulate the value (the ground case of a recursion) or just make another recursive call. – Pavel Zaichenkov Sep 15 '13 at 15:11
  • It is not a search, but a traversal. – Basile Starynkevitch Sep 15 '13 at 15:53

1 Answers1

1

Try a simple recursive function (doing a depth first traversal) like

 let rec mysum t = match t with
      Int x -> x
    | Node (l,r) -> mysum l + mysum r
 ;;

The first line might be let rec mysum = function (it is a matter of style).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547