我有这个简单的数据树:
data Tree = Leaf Int | Node [Tree]
我必须为这种类型开发折叠函数:
foldTree :: (Int -> a) -> ([a] -> a) -> Tree -> a
例如:
foldTree (+1) sum (Node[ (Leaf 2), (Leaf 3)])
将返回(2 + 1)+(3 + 1)= 7 对于叶子,我有:
foldTree f g (Leaf n) = (f n)
但我对开发节点的情况没有任何想法。
我是法国人,也为这些错误感到抱歉。
答案 0 :(得分:2)
查看范围及其类型可用的内容有时会有所帮助。这是一个解决方案:
foldTree f g (Leaf n) = (f n)
foldTree f g (Node subtrees) =
let as = map (foldTree f g) subtrees -- as :: [a]
in g as