Tail-recursion on trees

后端 未结 2 1901
借酒劲吻你
借酒劲吻你 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:43

    You can achieve a tail-recursive treefold using continuation-passing style:

    fun treefold1 f Leaf acc k = k acc
      | treefold1 f (Branch (left, a, right)) acc k =
        treefold1 f left acc (fn x => treefold1 f right (f(a, x)) k)
    
    fun treefold f t b = treefold1 f t b (fn x => x)
    

    For example:

    fun sumtree t = treefold op+ t 0
    
    val t1 = Branch (Branch(Leaf, 1, Leaf), 2, Branch (Leaf, 3, Leaf))
    
    val n = sumtree t1
    

    results in n = 6 as expected.

提交回复
热议问题