使用“mappend”时没有(Monoid [Char])的实例

时间:2017-03-18 12:01:01

标签: haskell

与你一起学习Haskell仿函数应用函子和monoid章并面临一个新问题,我的代码就在这里,即使我试图修复问题我也做不到,我的代码就在这里:

class Monoid m where  
    mempty :: m  
    mappend :: m -> m -> m  

instance Monoid a => Monoid (Maybe a) where  
    mempty = Nothing  
    Nothing `mappend` m = m  
    m `mappend` Nothing = m  
    Just m1 `mappend` Just m2 = Just (m1 `mappend` m2)  

main = print $ Nothing `mappend` Just "andy" 

这是我收到的错误消息:

  No instance for (Monoid [Char]) arising from a use of `mappend'
    Possible fix: add an instance declaration for (Monoid [Char])
    In the second argument of `($)', namely
      `Nothing `mappend` Just "andy"'
    In the expression: print $ Nothing `mappend` Just "andy"
    In an equation for `main':
        main = print $ Nothing `mappend` Just "andy")

提前谢谢你,Tamas

1 个答案:

答案 0 :(得分:5)

您的代码未提供Monoid [a]的定义(列表类型无关紧要)。通常,您将导入Data.Monoid,其中为您定义了类Monoid和许多有用的实例。但是,编写一个实例来解决您的直接问题是微不足道的。对mappend两个列表意味着什么?您只需连接两个列表。

instance Monoid [a] where
    mempty = []
    l1 `mappend` l2 = l1 ++ l2

现在您需要Monoid [a]的实例才能完全实现Monoid (Maybe [a])的定义。