An abstraction that inherits from a related Functors and related Applicative.

Monads extend the capabilities of these by adding the choice of how to sequence based on prior mapping of functions.

A monad implements two functions:

return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b

where return defaults to the pure function of the related Applicative if it is not explicitly implemented in the monad.

>>= unwraps a monadic value and applies a function to it, which returns a new monadic value.

Monads can be combined using the >> operator. m1 >> m2 means first run m1 and then run m2 while preserving any effects that were produced by m1 and return the result from running m2 with the effects from m1.

Monad Laws

In addition to implementing return and >>= monads must adhere to the following laws

return x >>= f = f x
mx >>= return = mx
(mx >>= f) >>= g = mx >>= (\x -> (f x >>= g))

Examples

instance Monad ((->) r) where
  -- General return :: a -> m a
  -- return :: a -> (r -> a)
  return = const
 
  -- General (>>=) :: m a -> (a -> m b) -> m b
  -- (>>=) :: (r -> a) -> (a -> (r -> b)) -> (r -> b)
  -- left:
  -- g :: r -> a
  -- f :: a -> (r -> b)
  -- g >>= f :: r -> b
  -- right:
  -- x :: r
  -- g x :: a
  -- \x -> g x :: r -> a
  -- f (g x) :: (r -> b)
  -- f (g x) x :: b
  -- \x -> f (g x) :: r -> b
  g >>= f = \x -> f (g x) x

Resources

https://www.adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html#monads