Type Error in Monad Definition

I am trying to learn about Monads in Haskell. Given the data type:

data XY a = X a | Y a

I would like to 'X a >>= f'return 'f a'and 'Y a >>= f'just to ignore 'f'and return 'Y a'.

This is the code I wrote:

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

and this is the compiler error I received:

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.

Could you help me understand what I am missing?

+3
source share
1 answer

Consider the type >>=:

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

In your case for Y a >>= fyou return XY a, not XY b. This is why a type error tells you that it cannot match what was expected bwith the actual a.

, , ( Y a), , XY , Y a. Monad Either, , .

+9

Source: https://habr.com/ru/post/1544695/


All Articles