what's this equation with lambda notation “ m >> n = m >>= \_ -> n ” in monad's declaration?

StackOverflow https://stackoverflow.com/questions/8690187

Domanda

class Monad m where
  return :: a -> m a
  (>>=)  :: m a -> (a -> m b) -> m b
  (>>)   :: m a -> m b -> m b
  m >> n = m >>= \_ -> n

  fail   :: String -> m a

I've never seen a equation(or function declaration?) in typeclass before. Why is there a equation in typeclass?

I know _ is a term for matching anything. but what m >>= \_ -> n match?

È stato utile?

Soluzione

It's a default implementation for the method. Unless your instance declaration contains an explicit implementation of (>>), that's the definition that will be used. Default methods are widespread if some method can be implemented using another method, but potentially there can be more efficient implementations for some datatypes.

m >>= \_ -> n

means the 'result' of m is fed to the function that ignores its argument and returns n no matter. It could also be written

m >>= const n

In the context of monads with effects, it's 'do m to have the effects, but ignore the return value, then do n'. That's what (>>) is meant to do there.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top