簡體   English   中英

沒有因使用'mappend'而引起的(Monoid [Char])實例

[英]No instance for (Monoid [Char]) arising from a use of `mappend'

與您一起學習Haskell函子,應用函子和monoids一章,面對一個新問題,即使我試圖解決無法解決的問題,我的代碼也在這里,我的代碼在這里:

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

提前謝謝你,塔瑪斯

您的代碼未提供Monoid [a]的定義(列表的類型無關緊要)。 通常,您將導入Data.Monoid ,其中為您定義了Monoid類和許多有用的實例。 但是,編寫實例來解決您的直接問題是微不足道的。 什么意思mappend兩個列表? 您只需串聯兩個列表。

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

現在,您具有完全實現Monoid (Maybe [a])定義所需的Monoid [a]實例Monoid (Maybe [a])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM