我有一个数据结构,尾递归在树上
datatype 'a tree = Leaf | Branch of 'a tree * 'a * 'a tree
,我想写一些为了遍历这棵树的功能。它没有关系,所以它可能是treefold : ('a * 'b -> 'b) -> 'b -> 'a tree -> 'b
。我可以写这个函数是这样的:
fun treefold f acc1 Leaf = acc1
| treefold f acc1 (Branch (left, a, right)) =
let val acc2 = treefold acc1 left
val acc3 = f (a, acc2)
val acc4 = treefold acc3 right
in acc4 end
但因为我不可避免地在最后一种情况下两个分支,这不是一个尾递归函数。
是否有可能创建一个,即允许类型签名被允许扩展以及花费多少?我也怀疑它是否值得尝试;也就是说,它在实践中是否会带来速度上的好处?
看到这个:http://stackoverflow.com/questions/9323036/tail-递归函数查找树的深度 – david