Monads

What are Monads trying to do?

A general pattern is a -> m b that takes a normal value and returns the value with some context, for example: a -> Maybe b could be a function that may fail; a -> IO b could wrap an operation which brings side-effect; a -> Either Ok Err could be a procedure that may return error message.

Now suppose we have 2 such functions f :: a -> m b and g :: b -> m c and we want to combine them to produce a -> m c.

Here comes the core of Monad, which is mainly perform computation on values with context (with dependency!).

Monad
1
2
3
4
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b
return :: a -> m a

Monad Laws

  1. Right Identity
1
m >>= return = m
  1. Left Identity
1
return a >>= f = f a
  1. Associativity
1
m >>= (\x -> k x >>= h) = (m >>= k) >>= h