定义Monad时Haskell类型错误

时间:2017-06-27 07:36:55

标签: haskell monads

我有一个类型Effect,表示对堆栈的影响。 Effect可以是成功的效果,可以修改堆栈并可选地生成输出,也可以是一个错误,可以记住堆栈失败时的堆栈效果。

data Effect a = Failure a | Effect a [Int]
instance Monad Effect where
    return s = Effect s []
    (Failure debugS) >>= _ = Failure debugS
    (Effect oldS oldO) >>= f =
        case f oldS of
            (Failure debugS) -> Failure debugS
            (Effect newS newO) -> Effect newS (newO ++ oldO)

绑定应该连接结果(以相反的顺序,我知道)。但是,目前GHC给出了以下错误消息:

example.hs:2:10:
    No instance for (Applicative Effect)
      arising from the superclasses of an instance declaration
    In the instance declaration for ‘Monad Effect’

example.hs:4:38:
    Couldn't match expected type ‘b’ with actual type ‘a’
      ‘a’ is a rigid type variable bound by
          the type signature for
            (>>=) :: Effect a -> (a -> Effect b) -> Effect b
          at example.hs:4:22
      ‘b’ is a rigid type variable bound by
          the type signature for
            (>>=) :: Effect a -> (a -> Effect b) -> Effect b
          at example.hs:4:22
    Relevant bindings include
      debugS :: a (bound at example.hs:4:14)
      (>>=) :: Effect a -> (a -> Effect b) -> Effect b
        (bound at example.hs:4:5)
    In the first argument of ‘Failure’, namely ‘debugS’
    In the expression: Failure debugS

我是Haskell的新手并且没有使用GHC的错误消息。我该如何纠正这个错误?

1 个答案:

答案 0 :(得分:2)

从GHC 7.10开始,由于Functor-Applicative-Monad Proposal,您很遗憾需要实施df['RES_J-1'] = df.groupby(['DPT_DATE','TRAIN_NO'])['RES_J-1'] .apply(lambda x: x.ffill().bfill()) MonadApplicative

您收到类型错误的原因是Functor的类型为:

>>=

这意味着您在中传递的功能会返回类型(>>=) :: Monad m => m a -> (a -> m b) -> m b 。但是,因为您回馈m b,这是Failure debugS类型,这是一种类型不匹配,因为它实际上迫使m a符合:

>>=

您返回的(>>=) :: Monad m => m a -> (a -> m a) -> m a -- Wrong! 必须与众不同。