Quantcast
Channel: Active questions tagged ocaml - Stack Overflow
Viewing all articles
Browse latest Browse all 527

tail-recursive maximum element in a binary tree in OCaml

$
0
0

I am practicing tail-recursion and I want to, given the type

type 'a tree = Leaf of 'a | Pair of 'a tree * 'a tree

and a function that that finds the maximum element in a binary tree

let rec tree_max t = match t with     | Leaf v -> v     | Pair (l,r) -> max (tree_max l) (tree_max r)

make the above function tail-recursive


I have tried

let rec tree_max t acc= match t with     | Leaf v -> acc    | Pair (l,r) -> (max (tree_max l) (tree_max r))::ACC

and I have also tried

let rec tree_max t acc= match t with     | Leaf v -> acc    | Pair (l,r) -> if (max (tree_max l) (tree_max l) = acc) then tree_max l acc else tree_max r acc

but they all yield syntax errors. Does anyone have an idea how to implement this?


Viewing all articles
Browse latest Browse all 527

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>