模棱两可的事件“折叠图”



我正在为以下数据结构实现可折叠:

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

当我实现折叠和折叠图时:

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。空的实例是"无明确实现"错误的来源(为什么这是一个警告,而不是我不知道的错误(。"模棱两可的发生"错误是因为编译器无法判断foldMap的递归电话是指隐式导入的Prelude.foldMap还是您的代码中的Main.foldMap

最新更新