【问题标题】:No instance for (Monoid [Char]) arising from a use of `mappend'没有使用 `mappend' 产生 (Monoid [Char]) 的实例
【发布时间】:2017-03-18 20:12:39
【问题描述】:

与你一起学习 Haskell 函子应用函子和幺半群章节并面临一个新问题,我的代码在这里,即使我试图解决我无法解决的问题,我的代码在这里:

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")

提前谢谢你,塔马斯

【问题讨论】:

  • 这只是说您没有 [Char] 的 Monoid 实例(或者,如果您愿意,也可以是 String)。你有什么?你不显示它。
  • 您已经定义了自己的类Monoid,而不是导入Data.Monoid,其中Monoid 的实例[a]

标签: haskell


【解决方案1】:

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

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

现在您有了完全实现Monoid (Maybe [a]) 定义所需的Monoid [a] 实例。

【讨论】:

  • 感谢@chepner,Tamas,您的答案很明确并且有效
  • @bling5630,这是一个挑战:为行为不同的列表编写至少三个不同的Monoid 实例,并证明它们中的每一个都满足幺半群定律。其中一些实例会有限制。
猜你喜欢
  • 2015-04-23
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多