【问题标题】:haskell: No instance for (Monoid Int) when use writer monad with haskell platform 2013 2.0.0haskell:当使用带有 haskell 平台 2.0.0 的 writer monad 时,没有 (Monoid Int) 的实例
【发布时间】:2014-11-20 04:09:46
【问题描述】:
module Main where
import Data.Char
import Control.Monad
import Control.Monad.Trans.Writer
import Control.Applicative
import Data.Monoid

wt :: Int -> Writer Int [String]
wt x=writer(["num:"++ show x],x)


addw::Writer Int [String]
addw = do
        a <- wt 2
        b <- wt 3
        return (a*b)

有2个错误:

No instance for (Monoid Int) arising from a do statement
    Possible fix: add an instance declaration for (Monoid Int)
    In a stmt of a 'do' block: a <- wt 2
    In the expression:
      do { a <- wt 2;
           b <- wt 3;
           return (a * b) }
    In an equation for `addw':
        addw
          = do { a <- wt 2;
                 b <- wt 3;
                 return (a * b) }


No instance for (Num [String]) arising from a use of `*'
    Possible fix: add an instance declaration for (Num [String])
    In the first argument of `return', namely `(a * b)'
    In a stmt of a 'do' block: return (a * b)
    In the expression:
      do { a <- wt 2;
           b <- wt 3;
           return (a * b) }

我使用带有最新 eclipsefp 的 eclipse 4.4 juno,haskell 平台 2013 2.0.0 包括 ghc 7.6.3,这段代码 sn-p 来自于学习你的 haskell for great good

【问题讨论】:

    标签: haskell types functional-programming ghc


    【解决方案1】:

    Int 本身并不是Monoid,因为有两种可能的实现方式:Sum 和Product。

    根据您的需要使用其中任何一个。


    哎呀。只需交换[String] 和Int。 Monad 的最后一个类型参数始终是它产生的值。

    【讨论】:

    • 成功了! wt::Int->Writer [String] Int wt x=writer(x,["num:"++ show x]) addw::Writer [String] Int addw = do a
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多