歧义出现“foldMap”

Ambiguous occurrence ‘foldMap’

我正在为以下数据结构实现 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.

当我实现该功能时,我会得到它已经存在的错误,但是当我不实现该功能时,我会收到该功能缺失的警告?我做错了什么?

您只需缩进 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。空实例是 "No explicit implementation" 错误的来源(我不知道为什么这是警告而不是错误)。 "ambiguous occurrence" 错误是因为编译器无法判断对 foldMap 的递归调用是指隐式导入的 Prelude.foldMap 还是代码中的 Main.foldMap