假设有以下相互递归的结构:
我该如何“机械地”生成使用累加器的尾递归foldl和使用延续的尾递归foldr?
我已经阅读了Scott's Recursive Types and Folds series,并且理解如何“机械地”为递归结构生成折叠。但是,我无法在Google上找到任何关于递归数据结构的“机械”的内容。
注:可以通过内联来消除上面的相互递归,但让我们保留它,因为它代表了tpetricek's Markdown parser中相互递归的简化版本。
type Tree<'a> =
| Empty
| Node of 'a * 'a Forest
and Forest<'a> =
| Nil
| Cons of 'a Tree * 'a Forest
目标:为此结构生成常见的消解函数:foldl、foldr和foldk。
我已经生成了原始消解函数,如下所示:
let rec foldTree fEmpty fNode fNil fCons =
function
| Empty -> fEmpty
| Node (a, f) -> fNode a (foldForest fEmpty fNode fNil fCons f)
and foldForest fEmpty fNode fNil fCons =
function
| Nil -> fNil
| Cons (t, f') -> fCons (foldTree fEmpty fNode fNil fCons t) (foldForest fEmpty fNode fNil fCons f')
我该如何“机械地”生成使用累加器的尾递归foldl和使用延续的尾递归foldr?
我已经阅读了Scott's Recursive Types and Folds series,并且理解如何“机械地”为递归结构生成折叠。但是,我无法在Google上找到任何关于递归数据结构的“机械”的内容。
注:可以通过内联来消除上面的相互递归,但让我们保留它,因为它代表了tpetricek's Markdown parser中相互递归的简化版本。