我完全不确定这是否是您要寻找的东西,但这似乎可以提供您想要的东西(有点)。
关键是只处理类型“内部”的内容,而将“外部”的内容由其他东西处理(一些抽象)
//val foldTree : 'a -> ('b -> 'c -> 'a) -> ('b Forest -> 'c) -> 'b Tree -> 'a
let foldTree fEmpty fNode fForest = function
Empty -> fEmpty
| Node (a, f) -> fNode a (fForest f)
// val foldForest : 'a -> ('b -> 'a -> 'a) -> ('c Tree -> 'b) -> 'c Forest -> 'a
let rec foldForest fNil fCons fTree =
let recurse = foldForest fNil fCons fTree
function
Nil -> fNil
| Cons (t, f) -> fCons (fTree t) (recurse f)
let foldForestAcc fNil fCons fTree =
let rec aux acc = function
Nil -> acc
| Cons (t, f) -> aux (fCons (fTree t) acc) f
aux fNil
let foldForestCont fNil fCons fTree =
let rec aux cont = function
Nil -> cont fNil
| Cons (t, f) -> aux (fCons (fTree t) >> cont) f
aux id
如果它更适合您的需求,这也是一种替代方法:
let fold fEmpty fNode fNil fCons =
let rec auxT = function
Empty -> fEmpty
| Node (a, f) -> fNode a (auxF f)
and auxF = function
Nil -> fNil
| Cons (t, f) -> fCons (auxT t) (auxF f)
auxT
let foldAcc fEmpty fNode fNil fCons =
let rec auxT acc = function
Empty -> acc
| Node (a, f) -> fNode a (auxF fNil f)
and auxF acc = function
Nil -> acc
| Cons (t, f) -> auxF (fCons (auxT fEmpty t) acc) f
auxT fEmpty
let foldCont fEmpty fNode fNil fCons =
let rec auxT cont = function
Empty -> cont fEmpty
| Node (a, f) -> cont (fNode a (auxF id f))
and auxF cont = function
Nil -> cont fNil
| Cons (t, f) -> auxF (cont >> fCons (auxT id t)) f
auxT id