Tail-recursion on trees

后端 未结 2 1898
借酒劲吻你
借酒劲吻你 2020-12-03 19:41

I have a data structure,

datatype \'a tree = Leaf | Branch of \'a tree * \'a * \'a tree

and I want to write a function that traverses this tr

2条回答
  •  暖寄归人
    2020-12-03 20:35

    Like @seanmcl writes, the systematic way to convert a function to be tail-recursive is to use continuation-passing style.

    After that you probably want to reify your continuations and use a more concrete data type, like a list for instance:

    fun treefoldL f init tree =
        let fun loop Leaf acc [] = acc
              | loop Leaf acc ((x, right) :: stack) =
                loop right (f(x,acc)) stack
              | loop (Branch (left, x, right)) acc stack =
                loop left acc ((x, right) :: stack)
        in  loop tree init [] end
    

提交回复
热议问题