Domanda

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 ?

È stato utile?

Soluzione

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).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top