The Monad
concept represents Applicative
s with the ability to flatten nested levels of structure.
Historically, Monads are a construction coming from category theory, an abstract branch of mathematics. The functional programming community eventually discovered how Monads could be used to formalize several useful things like side effects, which led to the wide adoption of Monads in that community. However, even in a multi-paradigm language like C++, there are several constructs which turn out to be Monads, like std::optional
, std::vector
and others.
Everybody tries to introduce Monad
s with a different analogy, and most people fail. This is called the Monad tutorial fallacy. We will try to avoid this trap by not presenting a specific intuition, and we will instead present what monads are mathematically. For specific intuitions, we will let readers who are new to this concept read one of the many excellent tutorials available online. Understanding Monads might take time at first, but once you get it, a lot of patterns will become obvious Monads; this enlightening will be your reward for the hard work.
There are different ways of defining a Monad; Haskell uses a function called bind
(>>=
) and another one called return
(it has nothing to do with C++'s return
statement). They then introduce relationships that must be satisfied for a type to be a Monad with those functions. Mathematicians sometimes use a function called join
and another one called unit
, or they also sometimes use other category theoretic constructions like functor adjunctions and the Kleisli category.
This library uses a composite approach. First, we use the flatten
function (equivalent to join
) along with the lift
function from Applicative
(equivalent to unit
) to introduce the notion of monadic function composition. We then write the properties that must be satisfied by a Monad using this monadic composition operator, because we feel it shows the link between Monads and Monoids more clearly than other approaches.
Roughly speaking, we will say that a Monad
is an Applicative
which also defines a way to compose functions returning a monadic result, as opposed to only being able to compose functions returning a normal result. We will then ask for this composition to be associative and to have a neutral element, just like normal function composition. For usual composition, the neutral element is the identity function id
. For monadic composition, the neutral element is the lift
function defined by Applicative
. This construction is made clearer in the laws below.
First, a Monad
must be both a Functor
and an Applicative
. Also, an implementation of flatten
or chain
satisfying the laws below for monadic composition must be provided.
ap
method for Applicatives
may be derived from the minimal complete definition of Monad
and Functor
; see below for more information.To simplify writing the laws, we use the comparison between functions. For two functions f
and g
, we define
With the usual composition of functions, we are given two functions \( f : A \to B \) and \( g : B \to C \), and we must produce a new function \( compose(g, f) : A \to C \). This composition of functions is associative, which means that
Also, this composition has an identity element, which is the identity function. This simply means that
This is probably nothing new if you are reading the Monad
laws. Now, we can observe that the above is equivalent to saying that functions with the composition operator form a Monoid
, where the neutral element is the identity function.
Given an Applicative
F
, what if we wanted to compose two functions \( f : A \to F(B) \) and \( g : B \to F(C) \)? When the Applicative
F
is also a Monad
, such functions taking normal values but returning monadic values are called monadic functions. To compose them, we obviously can't use normal function composition, since the domains and codomains of f
and g
do not match properly. Instead, we'll need a new operator – let's call it monadic_compose
:
\[ \mathtt{monadic\_compose} : (B \to F(C)) \times (A \to F(B)) \to (A \to F(C)) \]
How could we go about implementing this function? Well, since we know F
is an Applicative
, the only functions we have are transform
(from Functor
), and lift
and ap
(from Applicative
). Hence, the only thing we can do at this point while respecting the signatures of f
and g
is to set (for x
of type A
)
Indeed, f(x)
is of type F(B)
, so we can map g
(which takes B
's) on it. Doing so will leave us with a result of type F(F(C))
, but what we wanted was a result of type F(C)
to respect the signature of monadic_compose
. If we had a joker of type \( F(F(C)) \to F(C) \), we could simply set
and we would be happy. It turns out that flatten
is precisely this joker. Now, we'll want our joker to satisfy some properties to make sure this composition is associative, just like our normal composition was. These properties are slightly cumbersome to specify, so we won't do it here. Also, we'll need some kind of neutral element for the composition. This neutral element can't be the usual identity function, because it does not have the right type: our neutral element needs to be a function of type \( X \to F(X) \) but the identity function has type \( X \to X \). It is now the right time to observe that lift
from Applicative
has exactly the right signature, and so we'll take this for our neutral element.
We are now ready to formulate the Monad
laws using this composition operator. For a Monad
M
and functions \( f : A \to M(B) \), \( g : B \to M(C) \) and \( h : C \to M(D) \), the following must be satisfied:
which is to say that M
along with monadic composition is a Monoid where the neutral element is lift
.
Functor
Applicative
(free implementation of ap
)Monad
and Functor
are both satisfied, it is possible to implement ap
by setting hana::lazy
, hana::optional
, hana::tuple
Variables | |
constexpr auto | boost::hana::chain |
Feed a monadic value into a monadic computation.Given a monadic value and a monadic function, chain feeds the monadic value into the function, thus performing some Monad-specific effects, and returns the result. An implementation of chain must satisfy. More... | |
constexpr auto | boost::hana::flatten |
Collapse two levels of monadic structure into a single level.Given a monadic value wrapped into two levels of monad, flatten removes one such level. An implementation of flatten must satisfy. More... | |
constexpr auto | boost::hana::monadic_compose |
Composition of monadic functions.Given two monadic functions f and g , monadic_compose returns a new function equivalent to the composition of f with g , except the result of g is chain ed into f instead of simply passed to it, as with normal composition. monadic_compose satisfies. More... | |
template<typename M > | |
constexpr auto | boost::hana::tap |
Tap inside a monadic chain.Given a function f , tap<M> returns a new function which performs f on its argument and then returns the argument lifted in the M Monad . Combined with the property that chain(m, lift<M>) == m , this provides a way of executing an action inside a monadic chain without influencing its overall result. This is useful to e.g. insert debug statements or perform actions that are not tied to the chain but that need to be executed inside of it. More... | |
constexpr auto | boost::hana::then |
Sequentially compose two monadic actions, discarding any value produced by the first but not its effects. More... | |
constexpr auto boost::hana::chain |
#include <boost/hana/fwd/chain.hpp>
Feed a monadic value into a monadic computation.Given a monadic value and a monadic function, chain
feeds the monadic value into the function, thus performing some Monad-specific effects, and returns the result. An implementation of chain
must satisfy.
For a monad M
, given a monadic value of type M(A)
and a monadic function \( f : A \to M(B) \), chain
has the signature \( \mathtt{chain} : M(A) \times (A \to M(B)) \to M(B) \).
xs | A monadic value to be fed to the function f . |
f | A function taking a normal value in the xs structure, and returning a monadic value. This function is called as f(x) , where x is an element of the structure xs . |
constexpr auto boost::hana::flatten |
#include <boost/hana/fwd/flatten.hpp>
Collapse two levels of monadic structure into a single level.Given a monadic value wrapped into two levels of monad, flatten
removes one such level. An implementation of flatten
must satisfy.
For Sequence
s, this simply takes a Sequence
of Sequence
s, and returns a (non-recursively) flattened Sequence
.
For a Monad
M
, the signature of flatten
is \( \mathtt{flatten} : M(M(T)) \to M(T) \)
xs | A value with two levels of monadic structure, which should be collapsed into a single level of structure. |
constexpr auto boost::hana::monadic_compose |
#include <boost/hana/fwd/monadic_compose.hpp>
Composition of monadic functions.Given two monadic functions f
and g
, monadic_compose
returns a new function equivalent to the composition of f
with g
, except the result of g
is chain
ed into f
instead of simply passed to it, as with normal composition. monadic_compose
satisfies.
compose
, monadic_compose
does not generalize nicely to arities higher than one. Hence, only unary functions may be used with monadic_compose
.Given a Monad
M
and two functions \( f : B \to M(C) \) and \( g : A \to M(B) \), the signature is \( \mathtt{monadic\_compose} : (B \to M(C)) \times (A \to M(B)) \to (A \to M(C)) \).
f | A monadic function with signature \( B \to M(C) \). |
g | A monadic function with signature \( A \to M(B) \). |
constexpr auto boost::hana::tap |
#include <boost/hana/fwd/tap.hpp>
Tap inside a monadic chain.Given a function f
, tap<M>
returns a new function which performs f
on its argument and then returns the argument lifted in the M
Monad
. Combined with the property that chain(m, lift<M>) == m
, this provides a way of executing an action inside a monadic chain without influencing its overall result. This is useful to e.g. insert debug statements or perform actions that are not tied to the chain but that need to be executed inside of it.
f
function. Actually, side effects are the only reason why one might want to use tap
. However, one should not rely on the side effects being done in any specific order.M | The tag (a Monad ) of the monads in the tapped monadic chain. |
f | A function to be executed inside a monadic chain. It will be called as f(x) , where x is a value inside the previous monad in the chain. The result of f is always discarded. |
constexpr auto boost::hana::then |
#include <boost/hana/fwd/then.hpp>
Sequentially compose two monadic actions, discarding any value produced by the first but not its effects.
before | The first Monad in the monadic composition chain. The result of this monad is ignored, but its effects are combined with that of the second monad. |
xs | The second Monad in the monadic composition chain. |