不明确的'foldMap'

时间:2017-05-05 11:34:47

标签: haskell foldable

我正在为以下数据结构实现Foldable:

data Tree a = Leaf a | Node (Tree a) (Tree a) deriving Show

当我实现fold和foldMap时:

instance Foldable Tree where 

--fold :: Monoid a => Tree a -> a
fold (Leaf x) = x
fold (Node l r) = fold l `mappend` fold r

--foldMap :: Monoid b => (a -> b) -> Tree a -> b 
foldMap f (Leaf x) = f x
foldMap f (Node l r) = foldMap f l `mappend` foldMap f r

我会收到以下错误:

    Ambiguous occurrence ‘foldMap’
    It could refer to either ‘Main.foldMap’,
                             defined at Chapterh14.hs:57:1
                          or ‘Prelude.foldMap’,
                             imported from ‘Prelude’ at Chapterh14.hs:1:1
                             (and originally defined in ‘Data.Foldable’)

Chapterh14.hs:58:46:
    Ambiguous occurrence ‘foldMap’
    It could refer to either ‘Main.foldMap’,
                             defined at Chapterh14.hs:57:1
                          or ‘Prelude.foldMap’,
                             imported from ‘Prelude’ at Chapterh14.hs:1:1
                             (and originally defined in ‘Data.Foldable’)

Chapterh14.hs:71:13:
    Ambiguous occurrence ‘foldMap’
    It could refer to either ‘Main.foldMap’,
                             defined at Chapterh14.hs:57:1
                          or ‘Prelude.foldMap’,
                             imported from ‘Prelude’ at Chapterh14.hs:1:1
                             (and originally defined in ‘Data.Foldable’)

当我删除foldMap的定义时,我会收到以下警告:

    No explicit implementation for
      either ‘foldMap’ or ‘foldr’
    In the instance declaration for ‘Foldable Tree’
Ok, modules loaded: Main.

当我实现该函数时,我将得到它已经存在的错误,但是当我没有实现该函数时,我会收到一个警告,该函数丢失了?我做错了什么?

1 个答案:

答案 0 :(得分:4)

您只需缩进foldfoldMap声明,以便它们成为instance的一部分。

instance Foldable Tree where
    --fold :: Monoid a => Tree a -> a
    fold (Leaf x) = x
    fold (Node l r) = fold l `mappend` fold r

    --foldMap :: Monoid b => (a -> b) -> Tree a -> b
    foldMap f (Leaf x) = f x
    foldMap f (Node l r) = foldMap f l `mappend` foldMap f r

当你让它们缩进时,机器会看到一个空的instance声明和两个不相关的顶级函数foldfoldMap。空实例是"没有明确实现的来源"错误(为什么这是一个警告,而不是我不知道的错误)。 "模棱两可的事件"错误是因为编译器无法判断对foldMap的递归调用是指引用隐式导入的Prelude.foldMap还是代码中的Main.foldMap