Tail recursive function to find depth of a tree in Ocaml
I have a type tree defined as follows type 'a tree = Leaf of 'a | Node of 'a * 'a tree * 'a tree ;; I have a function to find the depth of the tree as follows let rec depth = function | Leaf x -> 0 | Node(_,left,right) -> 1 + (max (depth left) (depth right)) ;; This function is not tail recursive. Is there a way for me to write this function in tail recursive way? You can trivially do this by turning the function into CPS (Continuation Passing Style). The idea is that instead of calling depth left , and then computing things based on this result, you call depth left (fun dleft -> ...) , where