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!).
1 | class Monad m where |
Monad Laws
- Right Identity
1 | m >>= return = m |
- Left Identity
1 | return a >>= f = f a |
- Associativity
1 | m >>= (\x -> k x >>= h) = (m >>= k) >>= h |