I have the following implementation for a binary tree and a depth function to calculate its depth:
type 'a btree =
| Empty
| Node of 'a * 'a btree * 'a btree;;
let rec depth t = match t with
| Empty -> 0
| Node (_, t1, t2) -> 1 + Int.max (depth t1) (depth t2)
The problem here is that "depth" is recursive and can cause a stack overflow when the tree is too big.
I read about tail recursion and how it can be optimised into a while loop by the compiler to remove the stack call.
How would you make this function tail recursive or make it use a while/for loop instead?