Haskell Monad定义中的类型错误

Haskell Monad定义中的类型错误,haskell,monads,Haskell,Monads,我想了解哈斯克尔的单子。 给定数据类型: data XY a = X a | Y a 我想'xa>=f'返回'fa'和'yaa>=f'忽略'f'并返回'yaa' 这是我写的代码: 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:

我想了解哈斯克尔的单子。 给定数据类型:

data XY a = X a | Y a
我想
'xa>=f'
返回
'fa'
'yaa>=f'
忽略
'f'
并返回
'yaa'

这是我写的代码:

  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.

你能帮我理解我遗漏了什么吗?

考虑一下
>>=
的类型:

(>>=) :: XY a -> (a -> XY b) -> XY b
对于
Y a>>=f
,您返回的是
XY a
,而不是
XY b
。这就是为什么类型错误告诉您它不能将预期的
b
与实际的
a
匹配

通常,您尝试执行的操作(始终返回
Y a
)没有意义,因为
XY
只有一个类型参数,如果不同时更改值
Y a
,则无法更改该参数。请看一下,看看如何使用稍微不同的类型来完成这类工作