我正在尝试将 Brian 的二叉树折叠 ( http://lorgonblog.wordpress.com/2008/04/06/catamorphisms-part-two/ ) 用于申请多路树。
来自 Brian 的博客的总结:
数据结构:
type Tree<'a> =
| Node of (*data*)'a * (*left*)Tree<'a> * (*right*)Tree<'a>
| Leaf
let tree7 = Node(4, Node(2, Node(1, Leaf, Leaf), Node(3, Leaf, Leaf)),
Node(6, Node(5, Leaf, Leaf), Node(7, Leaf, Leaf)))
二叉树折叠函数
let FoldTree nodeF leafV tree =
let rec Loop t cont =
match t with
| Node(x,left,right) -> Loop left (fun lacc ->
Loop right (fun racc ->
cont (nodeF x lacc racc)))
| Leaf -> cont leafV
Loop tree (fun x -> x)
例子
let SumNodes = FoldTree (fun x l r -> x + l + r) 0 tree7
let Tree6to0 = FoldTree (fun x l r -> Node((if x=6 then 0 else x), l, r)) Leaf tree7
多路树版本 [不(完全)工作]:
数据结构
type MultiTree = | MNode of int * list<MultiTree>
let Mtree7 = MNode(4, [MNode(2, [MNode(1,[]); MNode(3, [])]);
MNode(6, [MNode(5, []); MNode(7, [])])])
折叠功能
let MFoldTree nodeF leafV tree =
let rec Loop tree cont =
match tree with
| MNode(x,sub)::tail -> Loop (sub@tail) (fun acc -> cont(nodeF x acc))
| [] -> cont leafV
Loop [tree] (fun x -> x)
示例 1 返回 28 - 似乎有效
let MSumNodes = MFoldTree (fun x acc -> x + acc) 0 Mtree7
示例 2
不运行
let MTree6to0 = MFoldTree (fun x acc -> MNode((if x=6 then 0 else x), [acc])) Mtree7
最初我认为MFoldTree
需要一个map.something
地方,但我让它与@
操作员一起工作。
对第二个示例的任何帮助和/或纠正我在MFoldTree
函数中所做的事情都会很棒!
干杯
杜西奥德