繁体   English   中英

定义Monad时Haskell类型错误

[英]Haskell Type Error when Defining Monad

我有一个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的错误消息。 我应该如何纠正这个错误?

从GHC 7.10开始,由于Functor-Applicative-Monad提案 ,您很不幸需要实现MonadApplicativeFunctor

您收到类型错误的原因是>>=的类型是:

(>>=) :: Monad m => m a -> (a -> m b) -> m b

这意味着您传入的函数将返回 mb类型。 但是,因为您还给了Failure debugS ,所以它的类型为ma ,这是类型不匹配的,因为它实际上迫使>>=符合以下条件:

(>>=) :: Monad m => m a -> (a -> m a) -> m a  -- Wrong!

您返回的debugS必须不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM