使用foldl遍历Haskell中的Tree

时间:2014-05-03 17:44:36

标签: haskell tree

我有以下代码:

data Tree a = ATree a [Tree a] 
            deriving Show

treeFold :: (b -> a -> b) -> b -> Tree a -> b
treeFold f acc (ATree a [])      = f acc a 
treeFold f acc (ATree a m)       = foldl (treeFold f acc) (f acc a) m

它应该遍历Tree的每个元素并将值应用于该值。但它给了我这个错误:

Couldn't match type `Tree a' with `Tree a -> b'
    Expected type: (Tree a -> b) -> a -> Tree a -> b
      Actual type: b -> a -> b
    In the first argument of `treeFold', namely `f'
    In the first argument of `foldl', namely `(treeFold f acc)'
    In the expression: foldl (treeFold f acc) (f acc a) m

2 个答案:

答案 0 :(得分:5)

foldl的第一个输入有Tree a -> b类型,但实际上应该有b -> Tree a -> b类型。在第一个论点中摆脱acc。

treeFold f acc (ATree a m) = foldl (treeFold f) (f acc a) m

答案 1 :(得分:3)

首先,请不要使用foldl。这几乎总是很糟糕,它是严格的堂兄foldl'是一个更好的表现和正确的尾递归函数。

在任何情况下,foldl都希望通过将treeFold应用于acc而使用累加器来提供它的功能,而只需使用foldl' (treeFold f)。< / p>