Tail recursive function to find depth of a tree in Ocaml

后端 未结 3 1966
别那么骄傲
别那么骄傲 2020-11-29 01:50

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

3条回答
  •  没有蜡笔的小新
    2020-11-29 01:59

    There's a neat and generic solution using fold_tree and CPS - continuous passing style:

    let fold_tree tree f acc =
      let loop t cont =
        match tree with
        | Leaf -> cont acc
        | Node (x, left, right) ->
          loop left (fun lacc ->
            loop right (fun racc ->
              cont @@ f x lacc racc))
      in loop tree (fun x -> x)
    
    let depth tree = fold_tree tree (fun x dl dr -> 1 + (max dl dr)) 0
    

提交回复
热议问题