【问题标题】:Type error in Monad definitionMonad定义中的类型错误
【发布时间】:2014-06-16 03:30:07
【问题描述】:

我正在尝试了解 Haskell 中的 Monads。 给定数据类型:

data XY a = X a | Y a

我希望 'X a >>= f' 返回 'f a' 和 'Y a >>= f' 以忽略 'f' 并返回 'Y a'。

这是我写的代码:

  4 instance Monad XY where
  5         return x = X x
  6         (X a) >>= f = f a
  7         (Y a) >>= f = Y a

这是我得到的编译器错误:

prog.hs:7:25:
    Couldn't match expected type `b' with actual type `a'
      `b' is a rigid type variable bound by
          the type signature for >>= :: XY a -> (a -> XY b) -> XY b
          at prog.hs:6:9
      `a' is a rigid type variable bound by
          the type signature for >>= :: XY a -> (a -> XY b) -> XY b
          at prog.hs:6:9
    In the first argument of `Y', namely `a'
    In the expression: Y a
    In an equation for `>>=': (Y a) >>= f = Y a
Failed, modules loaded: none.

你能帮我理解我缺少什么吗?

【问题讨论】:

    标签: haskell monads


    【解决方案1】:

    考虑>>=的类型:

    (>>=) :: XY a -> (a -> XY b) -> XY b
    

    对于Y a >>= f 的案例,您返回的是XY a,而不是XY b。这就是类型错误告诉您它无法将预期的b 与实际的a 匹配的原因。

    一般而言,您尝试执行的操作(始终返回 Y a)没有意义,因为 XY 只有一个类型参数,如果不更改值 Y a,您将无法更改。看看Monad instance for Either,看看如何使用稍微不同的类型来完成这种事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多