monad (in computer science)

> This entry is about [[monads]] as known from [[categorical algebra]] but in their application to [[computer science]]. See also at *[[monad (disambiguation)]]*.

***

+-- {: .rightHandSide}
+-- {: .toc .clickDown tabindex="0"}
### Context
#### Computation
+-- {: .hide}
[[!include constructivism - contents]]
=--
#### Categorical algebra
+-- {: .hide}
[[!include categorical algebra -- contents]]
=--
#### Type theory
+-- {: .hide}
[[!include type theory - contents]]
=--
=--
=--

# Contents
* table of contents
{: toc}

## Idea
 {#Idea}

In [[computer science]], a *([[comonad|co-]])[[monad]]* (or *([[co-Kleisli category|co-]])[[Kleisli triple]]*, or *(co-)[[extension system]]*) is a kind of [[data type]]-structure which describes "notions of computations" [[Moggi (1989)](#Moggi89), [Moggi (1991)](#Moggi91)] that may "have external effects or be subject to external contexts/causes" --- such as involving [[random access memory]], [[IO-monad|input/output]], [[exception monad|exception handling]], [[writer monad|writing to]] or [[reader monad|reading from]] global variables,  etc. --- as familiar from [[imperative programming]] but cast as "pure functions" with deterministic and [[verified programming|verifiable behaviour]], in the style of [[functional programming]].

In short, a ("[[extension system]]-style" [[Manes (1976), Ex. 3.12](#Manes76)] or "[[Kleisli triple]]-style" [[Moggi (1991), Def. 1.2](#Moggi91)]) *[[monad]]* in a given [[programming language]] consists of *assignments* (but see [below](#RefinedIdea)):

1. to any [[data type|data]] [[type]] $D$ of a new data type $\mathcal{E}(D)$ of "$D$-data with $\mathcal{E}$-effects",

1. to any [[pair]] of $\mathcal{E}$-effectful [[functions]] (programs) of the form $prog_{12} \,\colon\, D_1 \to \mathcal{E}(D_2)$ and $prog_{23} \,\colon\, D_2 \to \mathcal{E}(D_3)$ of an effective-composite function $bind^{\mathcal{E}} prog_{23} \;\circ\; prog_{12}(-) \,\colon\, D_1 \to \mathcal{E}(D_3)$ (their *binding* or *[[Kleisli composition]]*),

1. to any [[data type|data]] [[type]] $D$ of a function $ret^{\mathcal{E}}_D \;\colon\; D \to \mathcal{E}(D)$ assigning "trivial $\mathcal{E}$-effects",

such that the binding is [[associativity|associative]] and also [[unitality|unital]] with respect to the return operation, hence such that [[data types]] with $\mathcal{E}$-effectful programs between them constitute a [[category]] (the *[[Kleisli category]]* of the given effect/monad $\mathcal{E}$).

We now explain in more detail what this means and what it is good for.

### Basic idea: Monadic effects
 {#BasicIdea}

In [[programming language|programming]] it frequently happens that a [[program]] with "nominal" output [[data type]] $D$ *de facto* outputs data of some modified type $T(D)$ which accounts for "external effects" caused by the program, where
\[
  \label{MonadMapInIntroduction}
  D \;\mapsto\; \mathcal{E}(D)
\]
is some general operation sending [[data types]] $D$ to new data types $\mathcal{E}(D)$.

> For example, if alongside the computation of its nominal output data $d \colon D$ a program also writes a log message $msg \,\colon\,$ [[String (computer science)|String]], then its actual output data is the [[pair]] $(d, msg)$ of [[product type]] $Write(D) \,\coloneqq\, D \times String$.

> Or, dually, if the program may fail and instead "throw an [[exception]] message" $msg \,\colon\,$ [[String (computer science)|String]], then its actual output data is *either* $d \colon D$ *or* $msg \colon String$, hence is of [[coproduct type]] $Excep(D) \,\coloneqq\, D \sqcup String$.

Given such an $\mathcal{E}$-effectful program $prog_{12} \;\colon\; D_1 \to \mathcal{E}(D_2)$ and given a subsequent program $prog_{23} \,\colon\, D_2 \to \mathcal{E}(D_3)$ accepting nominal input data of type $D_2$ and itself possibly involved in further effects of type $\mathcal{E}(-)$, then the *naïve* [[composition]] of the two programs makes no sense (unless $\mathcal{E}(D) = D$ is actually the trivial sort of effect), but their evident *intended* composition is, clearly, obtained by:

1. first adjusting $prog_{23}$ via a given prescription

   \[
     \label{BindingLawInIntroduction}
     \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!
     prog \;\mapsto\; bind^{\mathcal{E}} prog
     \,,
   \]

   such that $bind^{\mathcal{E}} prog_{23} \,\colon\, \mathcal{E}(D_2) \to \mathcal{E}(D_3)$:

   1. does accept data of type $\mathcal{E}(D_2)$ and

   1. "acts as $prog_{23}$ while *carrying* any previous $\mathcal{E}$-effects along" (this intuition becomes a formal fact below in (eq:FreeEffectHandlingIsBinding));

1. then forming the naive [[composition]] $bind^{\mathcal{E}} prog_{23} \;\circ\;  prog_{12}$

{#BindAndReturnGraphics} as follows:

\begin{imagefromfile}
    "file_name": "KleisliCompositionOfEffectfulPrograms-230927.jpg",
    "width": "840",
    "unit": "px",
    "margin": {
        "top": -20,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

> (Beware that we are denoting by "$bind^{\mathcal{E}} prog (-)$" what in [[programming languages]] like [[Haskell]] [is denoted by](https://wiki.haskell.org/Monad#The_Monad_class) "`(-) >>= prog`"  aka "fish notation", eg. [Milewski 2019 p. 321](#Milewski19), and which some authors denote by an upper-star, "$prog^\ast\,$", e.g.  [Moggi (1991)](#Moggi91); [Uustalu (2021), lecture 1](#Uustalu21Lecture1), [p. 12](https://cs.ioc.ee/~tarmo/mgs21/mgs1.pdf#page=12).)

Depending on the intended behaviour of these programs, it remains to specify how exactly $bind^{\mathcal{E}} prog_{23}$ "carries $\mathcal{E}(-)$-effects along", hence what the "bind" operation (eq:BindingLawInIntroduction) does concretely.

> For instance, in the above example of a logging-effect, where $Write(D_2) \,\coloneqq\, D_2 \times String$, the evident way is to use the [[concatenation]]  $String \times String \xrightarrow{\; concat \;} String$ and set:

> $ bind^{Write} prog_{23}\;\coloneqq\; D_2 \times String \xrightarrow{ prog_{23} \times Id_{String} } D_3 \times String \times String \xrightarrow{ Id_{D_3} \times concat } D_3 \times String \,. $

> In the other example above, where the effect is the possible throwing of an [[exception]] message, the evident way to carry this kind of effect along is to use the [[codiagonal]] $\nabla \,\colon\, String \sqcup String \to String$, which amounts to keep forwarding the exception that has already been thrown, if any:

> $bind^{Excep} prog_{23} \;\coloneqq\; D_2 \sqcup String \xrightarrow{ prog_{23} \sqcup Id_{String} } D_3 \sqcup String \sqcup String \xrightarrow{ id_{D_3} \sqcup \nabla } D_3 \sqcup String \,.$

Whatever design choice one makes for how to "carry along effects", it must be consistent in that applying the method to a [[triple]] of $\mathcal{E}$-effectful programs which are nominally composable, then their effectful composition should be unambiguously defined in that it is [[associative]], satisfying the following [[equation]] -- here called the the first "monad law":

\[
  \label{AssociativityConditionInIntroduction}
  bind^{\mathcal{E}} prog_{34}
  \;\circ\;
  \Big(
    bind^{\mathcal{E}}
    prog_{23}
    \;\circ\;
    prog_{12}
  \Big)
  \;\;\;=\;\;\;
  bind^{\mathcal{E}}
  \Big(
    bind^{\mathcal{E}}
    prog_{34}
    \;\circ\;
    prog_{23}
  \Big)
  \;\circ\;
  prog_{12}
  \,.
\]

Finally, for such a notion of effectful programs to be usefully connected to "pure" programs without effects,  it ought to be the case that for any program $prog_{01} \,\colon\, D_0 \xrightarrow{\;} D_1$ that happens to have no $\mathcal{E}$-effects, we have a prescription for how to regard it as an $\mathcal{E}$-effectful program in a trivial way. For that purpose there should be defined an operation

\[
  \label{ReturnMapInIntroduction}
  ret_{D} \;\colon\; D \xrightarrow{\;} \mathcal{E}(D)
\]

which does nothing but "return" data of type $D$, but re-regarded as effectful $\mathcal{E}(D)$-data in a trivial way; so that we may construct the trivially effectful program $ret^{\mathcal{D}}_{D_1} prog_{01} \;\colon\; D_0 \xrightarrow{\;} \mathcal{E}(D_1)$.

> For instance, in the above example of log-message effects this would be the operation $D \to D \times String$ which assigns the [[empty set|empty]] [[string (computer science)|string]] $ret^{Write} \;\colon\; d \mapsto (d, \varnothing)$.

> In the other example above, of [[exception handling]], the trivial effect $D \to D \sqcup String$ is just not to throw an exception, which is just $ret^{Excep} \;\colon\; d \mapsto d$ (the right [[coprojection]] into the [[coproduct]]).

The final consistency condition (i.e. the remaining "monad law") then is that "carrying along trivial effects is indeed the trivial operation", i.e. that

\[
  \label{UnitalityInIntroduction}
  bind^{\mathcal{E}}
  prog_{01}
  \;\circ\;
  ret_{D_0}(-)
  \;=\;
  prog_{01}
  \;\;\;\;\;\;\;\;\;
  \text{and}
  \;\;\;\;\;\;\;\;\;
  bind^{\mathcal{E}}
  ret_{D_1}
  \;\circ\;
  prog_{01}(-)
  \;=\;
  prog_{01}
  \,.
\]

Notice that the [[associativity]] condition (eq:AssociativityConditionInIntroduction) and the [[unitality]] condition (eq:UnitalityInIntroduction) are jointly equivalent to saying that [[data types]] with [[hom-sets]] of $\mathcal{E}$-effectful programs between them, in the above sense, form a *[[category]]*. In [[category theory]] this is known as the *[[Kleisli category]]* $Kl(\mathcal{E})$ of a *[[monad]]* $\mathcal{E}$ on the [[category]] $Type$ of [[data types]] with programs between them:

\[
  \label{TheKleisliCategory}
  \begin{array}{rcl}
    Obj\Big( Kl(\mathcal{E}) \Big)
    &\;\;=\;\;&
    Obj\Big(
      Type
    \Big)
    \\
    Hom\Big( Kl(\mathcal{E}) \Big)\big(D_1,\, D_2\big)
    &\;\;=\;\;&
    Hom\Big(
      Type
    \Big)
    \big(
      D_1,
      \,
      \mathcal{E}(D_2)
    \big)
    \\
    (-) \circ_{\mathrm{Kl}(\mathcal{E})} (-)
    &\;\;=\;\;&
    (-) \circ_{Type} bind^{\mathcal{E}}(-)
    \,.
  \end{array}
\]

> Traditionally in [[category theory]], the [[axioms]] on [[monads]] are presented in a somewhat different way, invoking a monad "product" [[natural transformation]] $\mathcal{E} \circ \mathcal{E} \xrightarrow{ \mu } \mathcal{E}$ instead of the "binding" operation. One readily checks that these two axiomatic presentations of monads are in fact equal -- see (eq:TransformBetweenBindAndJoinInIntroduction) below --, but the above "[[Kleisli triple]]/[[extension system]]"-presentation is typically more relevant in the practice of [[functional programming]].

In summary, a choice of *assignments* (but see [below](#RefinedIdea)) to [[data types]] $D_i$ of

1. $\mathcal{E}(D) \;\colon\; Type$,

   namely of types of $\mathcal{E}$-effectful data of nominal type $D$ (eq:MonadMapInIntroduction);

2. $bind^{\mathcal{E}}_{D_1, D_2} \;\colon\;  Hom\big(D_1,\, \mathcal{E}(D_2)\big) \longrightarrow Hom\big(\mathcal{E}(D_1),\,\mathcal{E}(D_2)\big)$,

   namely of how to execute a prog while carrying along any previous effects (eq:BindingLawInIntroduction);

3. $ret^{\mathcal{E}}_D \;\colon\; D \to \mathcal{E}(D)$,

   namely of how to regard plain $D$-data as trivially effectful (eq:ReturnMapInIntroduction)

subject to:

1. the [[associativity]] condition (eq:AssociativityConditionInIntroduction)

1. the [[unitality]] condition (eq:UnitalityInIntroduction)

is called a *[[monad in computer science]]* (also: "[[Kleisli triple]]" in [[functional programming]]) and serves to encode the notion that all programs may be subject to certain *external effects* of a kind $\mathcal{E}$ that is specified by the above choices of monad operations.

Here, for the time being (but see [below](#RefinedIdea)), we write $Hom(D_1, D_2)$ for the *[[set]]* of programs/functions taking data of type $D_1$ to data of $D_2$ (the *[[hom set]]* in the plain [[category]] of [[types]]).

> The first running example above is known as the *[[writer monad]]*, since it encodes the situation where programs may have the additional effect of writing a message string into a given buffer.

> The other running example above is naturally called the *[[exception monad]]*.

\linebreak

**Relation to other familiar axioms for monads.**
The above Kleisli/extension-structure, making a [[Kleisli category|Kleisli-style]] [[monad in computer science]], may and often is encoded in different equivalent ways:

Alternatively postulating operations

1. $D \mapsto \mathcal{E}(D)$ (as before)

1. $fmap^{\mathcal{E}}_{D_1, D_2} \;\colon\; Hom\big(D_1 \to D_2\big) \longrightarrow Hom\big(\mathcal{E}(D_1), \mathcal{E}(D_2)\big)$

1. $ret^{\mathcal{E}}_D \;\colon\; D \to \mathcal{E}(D)$

1. $join^{\mathcal{E}}_D \;\colon\; \mathcal{E}\big( \mathcal{E}(D) \big) \to \mathcal{E}(D)$

such that

1. $fmap^{\mathcal{E}}$ is *[[functor|functorial]]* on [[data types]],

1. $join^{\mathcal{E}}$ is [[associativity|associative]] and [[unitality|unital]] (with respect to $ret$) as a [[natural transformation]],

yields the definition of *[[monad]]* more traditionally used in [[category theory]] (namely as a [[monoid object]] [[internalization|in]] [[endofunctors]], here  on the plain  [[category]] of [[data types]]).

Direct inspection shows that one may [[bijection|bijectively]] transmute such $bind$- and $join$-operators into each other by expressing them as the following composites (using [[category theory]]-notation, for instance "ev" denotes the [[evaluation map]]):

\[
  \label{TransformBetweenBindAndJoinInIntroduction}
  \begin{array}{ll}
  &
  fmap^{\mathcal{E}}_{D_1, D_2}
  \;\colon\;
  Hom\big(D_1, D_2\big)
  \xrightarrow{ ret \circ (-) }
  Hom\big(D_1,\, \mathcal{E}(D_2) \big)
  \xrightarrow{ bind }
  Hom\big( \mathcal{E}(D_1),\, \mathcal{E}(D_2) \big)
  \\
  &
  join^{\mathcal{E}}_D
  \;\colon\;
  \mathcal{E}\big( \mathcal{E}(D) \big)
  \xrightarrow{
    \big(
      id_{ \mathcal{E} \mathcal{E}(D) },
      name(id_{ \mathcal{E} D })
    \big)
  }
  \mathcal{E} \mathcal{E} D \times Hom\big( \mathcal{E}(D),\, \mathcal{E}(D) \big)
  \xrightarrow{ bind }
  \mathcal{E}(D)
  \\
  \text{and conversely:}
  \\
  &
  bind^{\mathcal{E}}_{D, D'}
  \;\colon\;
  \mathcal{E}(D) \times Hom\big( \mathcal{E}(D),\, \mathcal{E}(D')  \big)
  \xrightarrow{
    \big(
      id_{\mathcal{E} D}, fmap_{D, \mathcal{E} D'}
    \big)
  }
  \mathcal{E} (D) \times Hom\big( \mathcal{E}(D) , \mathcal{E}\mathcal{E}(D') \big)
  \xrightarrow{\;
    ev
  \;}
  \mathcal{E} \mathcal{E}(D')
  \xrightarrow{\; join \;}
  D'
  \,.
  \end{array}
\]

### Refined idea: Strong monads
 {#RefinedIdea}

But in fact, in [[functional programming]]-[[programming language|languages]] one typically considers an enhanced version of the above situation:

In these higher-order languages one has, besides the ([[hom-set|hom-]])*[[set]]* of programs/functions $Hom\big(D_1, \, D_2\big)$ also the actual *[[data type]]* of functions, namely the *[[function type]]* $D_1 \to D_2$, which in terms of [[relation between type theory and category theory|categorical semantics]] is the *[[internal hom]]-[[hom object|object]]* $Map(D_1, \, D_2)$ in the [[cartesian closed category]] of [[data types]]. Therefore, in such languages (like [[Haskell]]) the [[type]] of the binding operation for given [[data types]] $D_1$, $D_2$ is actually taken to be the [[function type]]/[[internal hom]]

$$
  \begin{array}{ll}
  bind^{\mathcal{E}}_{D_1, D_2}
  \;\colon\;
  &&
  \big(
     D_1 \to \mathcal{E}(D_2)
  \big)
  \to
  \big(
    \mathcal{E}(D_1)
    \to
    \mathcal{E}(D_2)
  \big)
  \\
  &\simeq &
  \mathcal{E}(D_1)
  \times
  \big(
     D_1 \to \mathcal{E}(D_2)
  \big)
  \to
    \mathcal{E}(D_2)
  \\
  & \simeq &
  \mathcal{E}(D_1)
  \to
  \Big(
    \big(
       D_1 \to \mathcal{E}(D_2)
    \big)
    \to
      \mathcal{E}(D_2)
  \Big)
  \end{array}
$$

> (where we used the [hom-isomorphism](adjoint+functor#InTermsOfHomIsomorphism) of the [[product]]$\dashv$[[internal hom]]-[[adjoint functors|adjunction]] to re-identify the [[types]] on the right)

which (beware) is traditionally written without many of the parenthesis, as follows:

$$
  bind^{\mathcal{E}}_{D_1, D_2}
  \;\colon\;
  \mathcal{E} D_1
    \to
  \big(
    D_1
    \to
    \mathcal{E} D_2
  \big)
  \to
  \mathcal{E} D_2
  \,.
$$

In general (except in the [[base topos]] of [[Sets]]), such an iterated [[function type]]/[[internal hom]] is richer than (certainly different from) the corresponding plain [[hom set]], and accordingly a "Kleisli triple" defined as above but with the binding operation typed in this [[internalization|internal]] way is *richer* or *stronger* [[structure]] than that of a plain [[monad]] on the underlying category of types: namely it is an *[[enriched monad]]* or [equivalently](enriched+monad#RelationToStrongMonads) a *[[strong monad]]*  with respect to the self-[[enriched category|enrichment]] of the [[symmetric monoidal closed category]] of types ([Moggi 1991 §3](#Moggi91), cf. [Goubault-Larrecq, Lasota & Nowak 2002](#GLLN08), [McDermott & Uustalu (2022)](#McDermottUustalu22)).

On such an [[enriched monad|enriched]]/[[strong monad]], the bind operation is defined as the following composite:

$$
  \mathcal{E}(D_1) \times \mathcal{E} Map(D_1,\,D_2)
    \xrightarrow{\; strength_{\mathcal{E}} \;}
  \mathcal{E}\big(D_1 \times Map(D_1, \, \mathcal{E} D_2) \big)
    \xrightarrow{
      \mathcal{E} eval_{D_1, \mathcal{E} D_2}
    }
  \mathcal{E} \mathcal{E} D_2
    \xrightarrow{\;
      \mu_{D_2}
    \;}
  \mathcal{E} D_2
  \,.
$$

In particular, monads as used in [[functional programming languages]] like [[Haskell]] are really strong/enriched monads, in this way.

In this case -- and in most discussions by default -- the [[symmetric monoidal closed category]] of types is assumed to be [[cartesian closed category|cartesian closed]] ("classical types") but in contexts of [[linear type theory]] (such as [[quantum computation]]) it may be non-cartesian (or both: cf. [[doubly closed monoidal category]]).

\linebreak

Yet more structure on effect-monads is available in [[dependent type theories]] with [[type universes]], where one may demand that the monad operation $D \mapsto T(D)$ is not just an [[endofunction]] on the [[set]] of [[types]], but an [[endomorphism]] of the [[type universe]]. At least for [[idempotent monads]] this case is further discussed at *[[reflective subuniverse]]* and *[[modal type theory]]* and maybe elsewhere.

### Further idea: Monad modules
 {#MonadModulesInIdeaSection}

Further in the practice of [[programming language|programming]]: if programs may cause external effects, as [above](#BasicIdea), then one will often want to have some of them *handle* these effects.

> This is particularly evident in the [above](#BasicIdea) running examples of *[[exceptions]]* whose whole design purpose typically is to be handled when they arise.

Since a "handling" of $\mathcal{E}$-effects should mean that these be done with and turned into pure data of some actual [[type]] $D$, an $\mathcal{E}$-effect handler on(to) a data type $D$ should primarily consist of a program of the form

$$
  \mathcal{E}(D) \to D
  \,.
$$

that handles effects produced by $\mathcal{E}$-effectful programs $D' \to \mathcal{E}(D)$, turning them into pure computations $D' \to D$.

But in addition, such a handler needs to handle effects that have been "carried along" (eq:BindingLawInIntroduction) from previous computations, even along otherwise in-effectful computations $prog_{0,1} \;\colon\; D_{0} \to D_{1}$; therefore all these need to be assigned handlers:

$$
  hndl^{\mathcal{E}}_{D_2} prog_{1,2}
  \;\colon\;
  \mathcal{E}(D_1) \to D_2
  \,.
$$

Of such choice of effect handling, consistency demands that:

1. first handling all previous effects carried along (eq:BindingLawInIntroduction) and then the newly produced effects by a given $prog \,\colon\, D \to \mathcal{E}(D')$ has the same result as letting $prog$ take care of carrying along previous effects by passing to $prog[-]$ and then handling the resulting accumulation at once:

1. handling the trivial effect ought to be no extra operation:

\[
  \label{AxiomsForEffectHandlers}
\]
\begin{imagefromfile}
    "file_name": "MonadicEffectHandlerConditions-221105b.jpg",
    "width": "560",
    "unit": "px",
    "margin": {
        "top": -20,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

A data structure consisting of such assignments $hndl^{\mathcal{E}}$ subject to these "laws" is known as an *Kleisli triple algebra* (e.g. [Uustalu (2021), Lec. 2](#Uustalu21Lecture2)) or *algebra over an extension system* (see [here](algebra+over+a+monad#ReferencesKleisliStyle)) for $\mathcal{E}$ and is bijectively the same as what in traditional [[category theory]] is known as an *[[algebra over a monad|algebra over $\mathcal{E}$]]* or *$\mathcal{E}$-algebra* or, maybe best: an *$\mathcal{E}$-module* or *$\mathcal{E}$-[[modal type]]*.

Given a [[pair]] of such $\mathcal{E}$-[[modal types]] $\big(D_1, hndl^{\mathcal{E}}_{D_1} \big)$, $\big(D_2, hndl^{\mathcal{E}}_{D_2} \big)$, a function $\phi \,\colon\, D_1 \to D_2$ is a *[[homomorphism]]* between them if the result of handling $\mathcal{E}$-effects before or after applying $\phi$ is the same, hence
if for all functions $f \,\colon\, D_0 \to D_1$ the following [[commuting diagram|diagram commutes]]:

\begin{imagefromfile}
    "file_name": "HomomorphismOfMonadiEffectHandlers-221105.jpg",
    "width": "350",
    "unit": "px",
    "margin": {
        "top": -20,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

\linebreak

{#FreeModales} **Free $\mathcal{E}$-effect handlers.** Notice that [above](#BasicIdea) we motivated already the binding operation (eq:BindingLawInIntroduction) as a kind of $\mathcal{E}$-effect handling: namely as the "carrying along" of previous $\mathcal{E}$-effects. This intuition now becomes a precise statement:

For any $D_2 \;\colon\; Type$ we may tautologically handle (eq:AxiomsForEffectHandlers) $\mathcal{E}$-effects by absorbing them into the data type $\mathcal{E}(D_2)$, with the effect-handler simply being the effect-binding operation (eq:BindingLawInIntroduction):

\[
  \label{FreeEffectHandlingIsBinding}
  hndl^{\mathcal{E}}_{\mathcal{E}(D_2)}
  \Big(
     D_1
     \xrightarrow{ prog }
     \mathcal{E}(D_2)
  \Big)
  \;\coloneqq\;
  bind^{\mathcal{E}}
  prog
  \;\colon\;
  \mathcal{E}(D_1)
  \to
  \mathcal{E}(D_2)
  \,.
\]

The $\mathcal{E}$-effect-handlers (eq:AxiomsForEffectHandlers) arising this way are called *[free](algebra+over+a+monad#FreeAlgebras)*.

The [[full subcategory]] of free $\mathcal{E}$-effect handlers among [[Eilenberg-Moore category|all]] $\mathcal{E}$-[[modal types]] is known as the *[[Kleisli category]]*. By the [Kleisli equivalence](Kleisli+category#KleisliEquivalence), this is [[equivalence of categories|equivalent]] to the (plain) category (eq:TheKleisliCategory) of $\mathcal{E}$-effectful programs that we started with. Here this means that:

* *Plain data types with $\mathcal{E}$-effectful programs betweem them are equivalently data types freely equipped with the structure of $\mathcal{E}$-effect handlers.*

which makes a lot of sense.

\linebreak

### Dual idea: Comonadic contexts
 {#DualIdeaComonadicCauses}

\begin{imagefromfile}
    "file_name": "Overton-CoMonadHaskell.jpg",
    "float": "right",
    "width": 550,
    "unit": "px",
    "margin": {
        "top": -40,
        "bottom": 20,
        "right": 0,
        "left": 30
    },
    "caption": "(from [Overton 2014](#Overton14))"
\end{imagefromfile}

By [[formal duality]], all of the above discussion has a dual version, where now (e.g. [Uustalu & Vene (2008)](#UustaluVene08), [POM13](#POM13), [GKOBU16](#GKOBU16), [KRU20](#KRU20)):

* [[comonads]] encode *computational contexts* (*co-effects*),

* their [[coproduct]] operation is the *duplication* (*co-join*) of contexts  which serves to *extend* (*co-bind*) contexts over consecutive programs,

* [[comodules over comonads]] are data structures that *provide* (*co-handle*) such context.

In more detail:

* Above we had that:

  * A [[Kleisli map]] for a [[monad]] $\mathcal{E}$ is a program

    $$
      prog \;\colon\; D \to \mathcal{E}(D')
    $$

    *causing* an external $\mathcal{E}$-effect.

  * A Kleisli-module for a [[monad]] $\mathcal{E}T$ is a prescription

    $$
      hdl^{\mathcal{E}}_D id_D \;\colon\; \mathcal{E}(D) \to D
    $$

    for *handling* such $\mathcal{E}$-effects.

* Now dually:

  * A [[co-Kleisli map]] for a [[comonad]] $\mathcal{C}$ is a program

    $$
      prog \;\colon\; \mathcal{C}(D) \to D'
    $$

    *subject to* an external $\mathcal{C}$-"*context*" ([Uustalu & Vene (2008)](#UustaluVene08), [POM13](#POM13))

    (a $\mathcal{C}$-*cause*).

  * A co-Kleisli co-module for a comonad $\mathcal{C}$ is a program

    $$
      prvd^{\mathcal{C}}_D id_D \;\colon\; D \to \mathcal{C}(D)
    $$

    *producing* or *providing* such $\mathcal{C}$-contexts.

     (cf. [[Uustalu (2021), Lect. 3, slide 9](#Uustalu21Lecture3)])

\begin{imagefromfile}
    "file_name": "CoKleisliCompOfContextfulPrograms-230815.jpg",
    "width": "800",
    "unit": "px",
    "margin": {
        "top": -20,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

\linebreak

### Syntactic idea: Do-notation
 {#DoNotation}

Finally, to turn all this into an efficient [[programming language]] one just has to declare a convenient [[syntax]] for denoting [[Kleisli composition]].

One such syntax is known as "*do notation*" (introduced with "`{...}`" instead of "`do`" by [Launchbury 1993 §3.3](#Launchbury93), then promoted by [[Mark Jones]] in the 1990s [[HHPW07, p. 25](Haskell#HHPW07)] and adopted by [[Haskell]] in [version 1.3](https://www.haskell.org/definition/from12to13.html#do), for review see [Benton, Hughes & Moggi 2002 p. 70](#BentonHughesMoggi02), [Milewski 2019 §20.3](#Milewski19)), which aims to jointly express:

1. successive Kleisli composition in words like "do this, do that, and return the result",

1. any intermediate bind-operation as "extracting" a $D$-datum $d$ out of an $\mathcal{E}(D)$-datum $E$ with notation `d <- E`

Syntactically, do-notation is the following [[syntactic sugar]] for combined [[Kleisli composition]] and [[bound variable|variable binding]]:

1. `do prog` $\;\;\equiv\;\;$ `prog`

2. `do prog1 prog2` $\;\;\equiv\;\;$ `prog1 bind (\_ -> prog2)`

3. `do (x <- prog1) prog2` $\;\;\equiv\;\;$ `prog1 bind (\x -> prog2)`

This is, first of all, a suggestive notation (in fact a "[[domain specific embedded programming language]]", see [there](domain+specific+embedded+programming+language#RelationToMonadicEffects)) for expressing effect-binding:

\begin{imagefromfile}
    "file_name": "EffectBindingViaDoNotation-230828.jpg",
    "width": "350",
    "unit": "px",
    "margin": {
        "top": -30,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

but thereby it furthermore provides a convenient means of expressing successive Kleisli-composition simply by successivley "calling" the separate procedures, much in the style of [[imperative programming]] (which thereby is emulated/encapsulated by pure [[functional programming]]):

\begin{imagefromfile}
    "file_name": "KleisliCompositeInDoNotation-230826.jpg",
    "width": "520",
    "unit": "px",
    "margin": {
        "top": -30,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

but the notation becomes more suggestive with the rule that the "`<-`"-symbols may notationally be suppressed for functions with trivial in- or out-put (ie. of [[unit type]] $\ast$) besides their $\mathcal{E}$-effect, as in this example:

\begin{imagefromfile}
    "file_name": "PureEffectKleisliCompositeInDoNotation-230826.jpg",
    "width": "520",
    "unit": "px",
    "margin": {
        "top": -30,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

This case brings out clearly how the ambient "`do`...`return`"-syntax block expresses the (Kleisli-)composition of any number of $\mathcal{E}$-effectful procedures.

On top of that the "`<-`"-syntax is meant to be suggestive of *reading out* a value. This is accurate imagery for the [[state monad]] (and its abstraction to the [[IO-monad]]), where from the two pasic operations of reading/writng a global variable
$$
  \array{
    read &\colon& W State(W)
    \\
    read &\equiv& w \mapsto (w,w)
  }
  \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;
  \array{
    write &\colon& W \to W State(\ast)
    \\
    write &\equiv& w \mapsto (w' \mapsto w)
  }
$$
any $W$-stateful program, such as the simple example
$$
  \array{
    inc &\colon& \mathbb{N}State(\ast)
    \\
    inc &\equiv& n \mapsto n+1
  }
$$
may be constucted in do-notation, such as:

\begin{imagefromfile}
    "file_name": "StatefulNumberIncrementInDONotation-230828.jpg",
    "width": 560,
    "unit": "px",
    "margin": {
        "top": -30,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

For a similar effect monad such as the [[list monad]] the analogous `do`-code for incrementing all entries in a list of numbers looks as follows:

\begin{imagefromfile}
    "file_name": "ListReadKleisliCompositeInDoNotation-230826.jpg",
    "width": "520",
    "unit": "px",
    "margin": {
        "top": -30,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

Here The `do`-notation on the right evokes the idea that in *each step* a number $n \colon \mathbb{N}$ is "read out" from MyList and then its increment returned --- but leaves linguistically implicit the idea that this operation is to be performed *for all elements* of the list and all results re-compiled into an output list.

Indeed, in general it is misleading to think of Kleisli composition as being about "reading out" data. What Kleisli composition is really about is acting on data that has *generators* and defining a program by what it does *on generators*, hence *for* a given generating datum:

\begin{imagefromfile}
    "file_name": "KleisliMapsActOnGeneratingData-23-828.jpg",
    "width": 560,
    "unit": "px",
    "margin": {
        "top": -30,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

Therefore the conceptually more accurate (if maybe less concise) program-linguistic reflection of the monadic effect-binding operation would be a "`for`...`do`"-block:

\begin{imagefromfile}
    "file_name": "ForDoNotation-230827c.jpg",
    "width": "420",
    "unit": "px",
    "margin": {
        "top": -20,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

In terms of such for-do-notation, the generic case that we started with above has the following syntactic rendering:

\begin{imagefromfile}
    "file_name": "KleisliCompositeInForDoNotation-230826.jpg",
    "width": "670",
    "unit": "px",
    "margin": {
        "top": -30,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

This syntax may be notationally less concise but it evokes rather closely what is actually going on in programming with monadic effects.

For example, the above operation of icrementing all numbers in a given list reads in `for`...`do`-notation as follows:

\begin{imagefromfile}
    "file_name": "ListIncrementViaForDo-280827b.jpg",
    "width": "750",
    "unit": "px",
    "margin": {
        "top": -20,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

neatly indicative of how the operation $+1$ is applied *for* every number $n$ found *in* the list.

(NB.: There is no clash with `for`...`do`-notation as used for loops in [[imperative programming]], since [[functional programming|functionally]] these are instead expressed by [[recursion]].)

The appropriateness of rendering effect binding as a `for`...`do`-expression becomes yet more pronounced in contexts of [[substructural logic|substructural]] [[type theory|typing contexts]] such as in [[linear type theory]], where the idea of "reading out" of monadic types via "`<-`"-notation becomes yet more dubious.

For example, consider the [[relative monad]] ([this example](relative+monad#LinearSpan)) which sends [[sets]] to the [[vector spaces]] that are their [[linear spans]]:

$$
  \array{
    \mathllap{\mathrm{Q} \;\;\colon\;\;}
    Set &\longrightarrow& Vect
    \\
    W &\mapsto& \underset{W}{\oplus} \mathbb{1}
  }
$$

with
$$
  \array{
    \mathllap{bind^{\mathrm{Q}} \;\;\colon\;\;}
    (W  \to \mathrm{Q}W')
    &\longrightarrow&
    (\mathrm{Q}W \to \mathrm{Q}W')
    \\
    \left(
      w
      \mapsto
      \left\vert \psi_w \right\rangle
    \right)
    &\mapsto&
    \left(
      \sum_w q_{{}_W} \left\vert w \right\rangle
      \,\mapsto\,
      \sum_w q_{{}_w} \left\vert \psi_w \right\rangle
    \right)
  }
$$

In this case the traditional `do`-notation would suggest that given a vector one may "read out" a basis element from it -- which does not make conceptual sense.

Instead, what's really happening is that to define a linear map $G \colon \mathrm{Q}W \to \mathscr{H}$ on a vector space equipped with a [[basis of a vector space|linear basis]] $W$ (literally: a set of free [generators](basis+of+a+vector+space#GeneratedVectorSpace)) it is sufficient to define this map *for* each basis-vector $\left\vert w \right\rangle$ --- and this is just what the `for`...`do`-notation for the $\mathrm{Q}$-monad expresses:

\begin{imagefromfile}
    "file_name": "LinearMapInForDoNotation-230828.jpg",
    "width": "150",
    "unit": "px",
    "margin": {
        "top": -30,
        "bottom": 20,
        "right": 0,
        "left": 10
    }
\end{imagefromfile}

\linebreak

## Examples
 {#Examples}

### Definable monads

Various monads are _definable_ in terms of standard [[type formation|type-forming operations]] (such as [[product types]], [[function types]], etc.). These include the following (cf. [Moggi 1991, Exp. 1.1](#Moggi91)):

* The *[[maybe monad]]* encodes possible controlled failure of a program to execute.

* An *[[exception monad]]*, more generally, encodes possible controlled failure together with the output of an error "message" in the general form of data of some type.

* The *[[reader monad]]* and *[[coreader comonad]]* both encode reading out a global parameter.

* The *[[writer monad]]* and *[[cowriter comonad]]* both encode writing *consecutively* into a global resource, such as for a [[stream]].

* The *[[state monad]]* encodes the possibility of *consecutive reading and re-setting* a global parameter  -- this provides a notion of *[[random access memory]]*.

* The *[[costate comonad]]* encodes a way (a "[[lens in computer science|lens]]") to read and write fields in [[databases]].

* The *[[continuation monad]]* encodes [[continuation-passing style]] of program execution.

* The *[[selection monad]]* encodes selecting a value of a type depending on the values of some function on it.

#### State monad and Random access memory
 {#StateMonad}

A [[functional program]] with input of [[type]] $D$, output of [[type]] $D'$ and *mutable state $W$* is a [[function]] ([[morphism]]) of [[type]] $D \times W \longrightarrow D' \times W$ -- also called a *[[Mealy machine]]* (see [there](Mealy+machine#MealyMachinesAsEffectfulMaps)).

Under the ([[Cartesian product]] $\dashv$ [[internal hom]])-[[adjunction]] ([[currying]]) this is equivalently given by its [[adjunct]], which is a function of type $D \longrightarrow [W, W \times D' ]$. Here the operation $[W, W\times (-)]$ is the [[monad]] induced by the above adjunction and this latter function is naturally regarded as a morphism in the [[Kleisli category]] of this monad. This monad $[W, W\times (-)]$ is called the _[[state monad]]_ for mutable states of type $W$:

<center>
<img src="/nlab/files/State-Effectful-Program-230804.jpg" width="600">
</center>

#### Maybe monad and Controlled failure

The **[[maybe monad]]** is the operation $X \mapsto X \coprod \ast$. The idea here is that a function $X \longrightarrow Y$ in its [[Kleisli category]] is in the original category a function of the form $X \longrightarrow Y \coprod \ast $ so either returns indeed a value in $Y$ or else returns the unique element of the [[unit type]]/[[terminal object]] $\ast$. This is then naturally interpreted as "no value returned", hence as indicating a "failure in computation".

#### Exception monad and Exception handling

(...) [[exception monad]] (...)

#### Continuation monad and Continuation-passing

The [[continuation monad]] on a given type $S$ acts by $X \mapsto [[X,S],S]$.

(...)

### Axiomatic monads

Other monads may be supplied "axiomatically" by the programming language, meaning that they are data structures [[type|typed]] as monads, but whose actual type formation, binding- and return-operations are special purpose operations provided by the programming environment.

This includes:

* the *[[IO monad]]* in [[Haskell]],

* the *[[completion monad]]*, as in [[constructive analysis]], used for dealing for instance with [[real numbers]].

In this vein:

* Equipping [[homotopy type theory]] (say implemented as a programming language concretely in [[Coq]] or [[Agda]]) with two axiomatic [[idempotent monads]], denoted $\sharp$ and $\Pi$, with some additional data and relations, turns it into _[[cohesive homotopy type theory]]_. See also at *[Agda flat](Agda#AgdaFlat)* and at *[[modal type theory]]*.

## Related concepts

* [[extension system]]

  * [[relative monad]]

  * [[polymonad]]

* [[relation between type theory and category theory]], [[categorical semantics]], [[categorical logic]]

* Examples of (co)monads in ([[homotopy type theory|homotopy]]) [[type theory]] involve in particular _[[modal operators]]_ as they  appear in

  * [[modal logic]]/[[modal type theory]]/[[computational type theory]].

  See also:

  * [[adjoint modality]].

* For an approach to composing monads, see

  * [[monad transformer]]

* Another approach to modelling side effects in [[functional programming languages]] are

  [[algebraic side effects]]

* [[free monad|Free monads]] in computer science appear in the concepts of

  * [[initial algebra for an endofunctor]]

  * [[terminal coalgebra for an endofunctor]]

* Other generalizations are:

  * [[arrow (in computer science)]]

  * [[applicative functor]]

* There is also: [[monad (in linguistics)]]

## References

### General
 {#ReferencesGeneral}

The [[extension system]]-style presentation of monads as used in computer science is briefly mentioned in:

* {#Manes76} [[Ernest G. Manes]], Sec 3, Ex. 12 (p. 32) of: *Algebraic Theories*, Springer (1976) [[doi:10.1007/978-1-4612-9860-1](https://doi.org/10.1007/978-1-4612-9860-1)]

and expanded on in

* {#MarmolejoWood10} [[Francisco Marmolejo]], [[Richard J. Wood]], *Monads as extension systems -- no iteration is necessary*, [[TAC]] **24** 4 (2010) 84-113 [[tac:24-04](http://www.tac.mta.ca/tac/volumes/24/4/24-04abs.html)]

but not related there to computation.

The original observation of monads as "notions of computation" is:

* {#Moggi89} [[Eugenio Moggi]], *Computational lambda-calculus and monads*, in: *Proceedings of the Fourth Annual Symposium on Logic in Computer Science* (1989) 14-23 [[doi:10.1109/LICS.1989.39155](https://doi.org/10.1109/LICS.1989.39155)]

* {#Moggi89Abstract} [[Eugenio Moggi]], *An abstract View of Programming Languages*, LFCS report ECS-LFCS-90-113 (1989) [[web](http://www.lfcs.inf.ed.ac.uk/reports/90/ECS-LFCS-90-113), [[Moggi-AbstractView.pdf:file]]]

  > (considers also [transformations of monads](monad#BicategoryOfMonads) in Def. 4.0.8)

* [[Philip Wadler]], *Comprehending Monads*, in _Conference on Lisp and functional programming_, ACM Press (1990) [[[WadlerMonads.pdf:file]], [doi:10.1145/91556.91592](https://doi.org/10.1145/91556.91592)]

* {#Moggi91} [[Eugenio Moggi]], *Notions of computation and monads*, Information and Computation, **93** 1 (1991) [<a href="https://doi.org/10.1016/0890-5401(91)90052-4">doi:10.1016/0890-5401(91)90052-4</a>, [pdf](http://www.disi.unige.it/person/MoggiE/ftp/ic91.pdf)]

* [[Philip Wadler]], *The essence of functional programming*, *POPL '92: Principles of programming languages* (1992) 1-14 [[doi:10.1145/143165.143169](https://doi.org/10.1145/143165.143169), [pdf](https://jgbm.github.io/eecs762f19/papers/wadler-monads.pdf)]

Further discussion:

* [[Gordon Plotkin]], [[John Power]], *Notions of Computation Determine Monads*, in: *Foundations of Software Science and Computation Structures* FoSSaCS 2002, Lecture Notes in Computer Science **2303**, Springer (2002) [[doi:10.1007/3-540-45931-6_24](https://doi.org/10.1007/3-540-45931-6_24), [era:1842/196](https://era.ed.ac.uk/handle/1842/196)]

On the impact of [Moggi (1991)](#Moggi91):

* [[Martin Hyland]], [[John Power]], §6 of: *The Category Theoretic Understanding of Universal Algebra: Lawvere Theories and Monads*, Electronic Notes in Theor. Comp. Sci. **172** (2007) 437-458 [[doi:10.1016/j.entcs.2007.02.019](https://doi.org/10.1016/j.entcs.2007.02.019), [preprint](https://www.dpmms.cam.ac.uk/~martin/Research/Publications/2007/hp07.pdf)]

Origin of the [[do-notation]] for [[Kleisli composition]] of effectful programs:

* {#Launchbury93} [[John Launchbury]], §3.3 in: *Lazy imperative programming*, Proceedings of *ACM Sigplan Workshop on State in Programming Languages*, Copenhagen (1993) [[pdf](https://launchbury.files.wordpress.com/2019/01/lazy-imperative-programming.pdf), [[Launchbury-LazyImperative.pdf:file]]]

Introducing the notion of [[monad transformers]]:

* {#Espinosa94} [[David A. Espinosa]], §3.2 in: *Building Interpreters by Transforming Stratified Monads* (1994) [[pdf](https://github.com/davidespinosa01/papers/blob/master/E/Espinosa%20David/espinosa-stratified-monads.pdf), [[Espinosa-StratifiedMonads.pdf:file]]]

* {#Espinosa95} [[David A. Espinosa]], §2.6 in: *Semantic Lego*, PhD thesis, Columbia University (1995) [[pdf](https://github.com/davidespinosa01/papers/blob/master/E/Espinosa%20David/espinosa-stratified-monads.pdf), [[Espinosa-SemanticLego.pdf:file]], slides:[pdf](https://github.com/davidespinosa01/papers/blob/346c2ded6af78805701106d51daee8f7a756c948/E/Espinosa%20David/espinosa-thesis-slides.pdf), [[Espinosa-SemanticLego-slides.pdf:file]]]

* {#LiangHudakJones95} Sheng Liang, [[Paul Hudak]], [[Mark Jones]], *Monad transformers and modular interpreters*, POPL '95 (1995) 333–343 [[doi:10.1145/199448.199528](https://doi.org/10.1145/199448.199528)]

More (early) literature is listed here:

* [[David A. Espinosa]], *[Effects bibliography](https://github.com/davidespinosa01/effects-bibliography)*

In the generality of [[relative monads]]:

* [[Thorsten Altenkirch]], [[James Chapman]], [[Tarmo Uustalu]], Section 2 of: *Monads need not be endofunctors*, Logical Methods in Computer Science **11** 1:3 (2015) 1–40 [[arXiv:1412.7148](https://arxiv.org/abs/1412.7148), [pdf](http://www.cs.nott.ac.uk/~txa/publ/jrelmon.pdf), <a href="https://doi.org/10.2168/LMCS-11(1:3)2015">doi:10.2168/LMCS-11(1:3)2015</a>]

The dual notion of [[comonads in computer science]] as modelling *contexts*:

* {#UustaluVene08}  [[Tarmo Uustalu]], [[Varmo Vene]], *Comonadic Notions of Computation*, Electronic Notes in Theoretical Computer Science **203** 5 (2008) 263-284 [[doi:10.1016/j.entcs.2008.05.029](https://doi.org/10.1016/j.entcs.2008.05.029)]

* {#POM13} [[Tomas Petricek]], [[Dominic Orchard]], [[Alan Mycroft]], *Coeffects: Unified Static Analysis of Context-Dependence*, in: *Automata, Languages, and Programming. ICALP 2013*, Lecture Notes in Computer Science **7966** Springer (2013) [[doi:10.1007/978-3-642-39212-2_35](https://doi.org/10.1007/978-3-642-39212-2_35)]

* {#Overton14} David Overton, *Comonads in Haskell* (2014) [[web](https://speakerdeck.com/dmoverton/comonads-in-haskell), [[Overton-ComonadsHaskell.pdf:file]]]

  > (in [[Haskell]])

on codo-notation for comonadic contexts:

* [[Dominic Orchard]], [[Alan Mycroft]], *A Notation for Comonads*, in: *Implementation and Application of Functional Languages. IFL 2012*, Lecture Notes in Computer Science **8241** [[doi:10.1007/978-3-642-41582-1_1](https://doi.org/10.1007/978-3-642-41582-1_1)]

and emphasis on the combination of [[monads]], [[comonads]] and [[graded modalities]]:

* {#GKOBU16} Marco Gaboardi, [[Shin-ya Katsumata]], [[Dominic Orchard]], Flavien Breuvart, [[Tarmo Uustalu]], *Combining effects and coeffects via grading*, ICFP 2016: Proceedings of the 21st ACM SIGPLAN International Conference on Functional Programming (2016) 476–489 [[doi:10.1145/2951913.2951939](https://doi.org/10.1145/2951913.2951939), [talk abstract](https://icfp16.sigplan.org/details/icfp-2016-papers/31/Combining-Effects-and-Coeffects-via-Grading), [video rec](https://www.youtube.com/watch?v=l1ZNMT3fQCo)]

* {#KRU20} [[Shin-ya Katsumata]], Exequiel Rivas, [[Tarmo Uustalu]], LICS (2020) 604-618 *Interaction laws of monads and comonads* [[arXiv:1912.13477](https://arxiv.org/abs/1912.13477), [doi:10.1145/3373718.3394808](https://doi.org/10.1145/3373718.3394808)]

The identification of (co)effect handling with ([[comodule over a comonad|co]])[[modules over a monad|modales]] over the given (co)monad:

* [[Gordon D. Plotkin ]], [[Matija Pretnar]], *Handling Algebraic Effects*, Logical Methods in Computer Science, **9** 4 (2013) lmcs:705 [[arXiv:1312.1399](https://arxiv.org/abs/1312.1399), <a href=" https://doi.org/10.2168/LMCS-9(4:23)2013">doi:10.2168/LMCS-9(4:23)2013</a>]

* Ohad Kammar, Sam Lindley, Nicolas Oury, *Handlers in action*, ACM SIGPLAN Notices **48** 9 (2013) 145–158 [[doi:10.1145/2544174.2500590](https://doi.org/10.1145/2544174.2500590)]

{#ReferencesInActualPorgrammingLanguages} Discussion in actual [[programming languages]] such as [[Haskell]]:

* {#BentonHughesMoggi02} [[Nick Benton]], [[John Hughes]], [[Eugenio Moggi]], *Monads and Effects*, in: *Applied Semantics*, Lecture Notes in Computer Science **2395**, Springer (2002) 42-122 [[doi:10.1007/3-540-45699-6_2](https://doi.org/10.1007/3-540-45699-6_2)]

* {#Milewski19} [[Bartosz Milewski]] (compiled by Igal Tabachnik), "Monads: Programmer's Definition", §20 in: *Category Theory for Programmers*, Blurb (2019) [[pdf](https://github.com/hmemcpy/milewski-ctfp-pdf/releases/download/v1.3.0/category-theory-for-programmers.pdf), [github](https://github.com/hmemcpy/milewski-ctfp-pdf), [webpage](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/), [ISBN:9780464243878](https://www.blurb.com/b/9621951-category-theory-for-programmers-new-edition-hardco)]

* {#Milewski23} [[Bartosz Milewski]], §14 in: *The Dao of Functional Programming* (2023) [[pdf](https://github.com/BartoszMilewski/Publications/blob/master/TheDaoOfFP/DaoFP.pdf), [github](https://github.com/BartoszMilewski/Publications/tree/master/TheDaoOfFP)]

and [[Scala]]:

* {#Winitzki22} [[Sergei Winitzki]], Section 10 of: *The Science of Functional Programming -- A tutorial, with examples in Scala* (2022) [[leanpub:sofp](https://leanpub.com/sofp), [github:sofp](https://github.com/winitzki/sofp)]

Further discussion/exposition of the notion and application of (co)monads in computer science:

* {#BrookesGeva91} [[Stephen Brookes]], Shai Geva, *Computational Comonads and Intensional Semantics*, CMU-CS-91-190 (1991) [[[BrookersGeva-ComputationalComonads.pdf:file]]]

* [[Philip Wadler]], *Monads for functional programming*, in M. Broy (eds.) *Program Design Calculi* NATO ASI Series, **118** Springer (1992) [[doi;10.1007/978-3-662-02880-3_8](https://doi.org/10.1007/978-3-662-02880-3_8), [pdf](https://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf)]
* Philip Mulry, _Monads in semantics_ , ENTCS **14** (1998) pp.275-286.

* {#BrookesVanStone93} [[Stephen Brookes]],  [[Kathryn Van Stone]], *Monads and Comonads in Intensional Semantics* (1993) [[dtic:ADA266522](https://apps.dtic.mil/sti/citations/ADA266522), [pdf](https://www.cs.cmu.edu/~brookes/papers/MonadsComonads.pdf), [[BrookesVanStone-CoMonads.pdf:file]]]

  > (with [[distributive law]] of comonad over monad)

* [[John Hughes]], section 2 of: _Generalising Monads to Arrows_, Science of Computer Programming (Elsevier) 37 (1-3): 67–111. (2000) ([pdf](http://pdn.sciencedirect.com/science?_ob=MiamiImageURL&_cid=271600&_user=10&_pii=S0167642399000234&_check=y&_origin=search&_zone=rslt_list_item&_coverDate=2000-05-31&wchp=dGLzVlk-zSkWb&md5=fa91ab4ffc136b0cedc52318c7c249be&pid=1-s2.0-S0167642399000234-main.pdf))

* {#Harper} [[Robert Harper]], _Of course ML Has Monads!_ (2011) ([web](http://existentialtype.wordpress.com/2011/05/01/of-course-ml-has-monads/))

* {#Benton15} [[Nick Benton]], _Categorical Monads and Computer Programming_, in: *[Impact150: stories of the impact of mathematics](https://www.lms.ac.uk/2015/impact150-stories-impact-mathematics)*. London Mathematical Society (2015)  [[pdf](https://www.lms.ac.uk/sites/lms.ac.uk/files/2.%20Benton%20-%20Categorical%20Monads%20and%20Computer%20Programming.pdf), [[Benton-CategoricalMonads.pdf:file]], [doi:10.1112/i150lms/t.0002](https://www.lms.ac.uk/2015/impact150-stories-impact-mathematics)]

* {#Riehl17} [[Emily Riehl]], *A categorical view of computational effects*, talk at *[C$\circ$mp$\circ$se$\colon\!\colon$Conference](https://www.composeconference.org/2017/)* (2017) [[pdf](http://www.math.jhu.edu/~eriehl/compose.pdf), [[Riehl-ComputationalEffects.pdf:file]]]

* Rob Norris, *Functional Programming with Effects*, talk at
*Scala Days 2018* [video: [YT](https://youtu.be/30q6BkBv5MY)]

* {#Uustalu21} [[Tarmo Uustalu]], lecture notes for [MGS 2021](https://staffwww.dcs.shef.ac.uk/people/G.Struth/mgs21.html) (2021):

  {#Uustalu21Lecture1} *Monads and Interaction Lecture 1* [[pdf](https://cs.ioc.ee/~tarmo/mgs21/mgs1.pdf), [[Uustalu-Monads1.pdf:file]]]

  {#Uustalu21Lecture2} *Monads and Interaction Lecture 2* [[pdf](https://cs.ioc.ee/~tarmo/mgs21/mgs2.pdf), [[Uustalu-Monads2.pdf:file]]]

  {#Uustalu21Lecture3} *Monads and Interaction Lecture 3* [[pdf](https://cs.ioc.ee/~tarmo/mgs21/mgs3.pdf), [[Uustalu-Monads3.pdf:file]]]

  {#Uustalu21Lecture4} *Monads and Interaction Lecture 4* [[pdf](https://cs.ioc.ee/~tarmo/mgs21/mgs4.pdf), [[Uustalu-Monads4.pdf:file]]]

* Christina Kohl, Christina Schwaiger, *Monads in Computer Science* (2021) [[pdf](https://www.uibk.ac.at/mathematik/algebra/staff/fritz-tobias/ct2021_course_projects/category_theory.pdf), [[KohlSchwaiger-Monads.pdf:file]]]

See also:

* Wikipedia, _<a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)">Monad (functional programming)</a>_

* Wikipedia, *<a href="https://en.wikipedia.org/wiki/Side_effect_(computer_science)">Side_effect_(computer_science)</a>*

The specification of [[monads]] in [[Haskell]] is at:

* [The Haskell programming language](http://www.haskell.org/haskellwiki/Haskell),

  * *[Monad](https://wiki.haskell.org/Monad)*

  * *[Monad laws](http://www.haskell.org/haskellwiki/Monad_laws)*

and an exposition of [[category theory]] and monads in terms of Haskell is in

* WikiBooks, _[Haskell/Category](http://en.wikibooks.org/wiki/Haskell/Category_theory)_

Further on the issue of the CS-style monads really being [[strong monads]]:

* {#GLLN08} [[Jean Goubault-Larrecq]], [[Slawomir Lasota]], [[David Nowak]], *Logical Relations for Monadic Types*, Mathematical Structures in Computer Science, **18** 6 (2008) 1169-1217 [[arXiv:cs/0511006](https://arxiv.org/abs/cs/0511006), [doi:10.1017/S0960129508007172](https://doi.org/10.1017/S0960129508007172)]

* {#McDermottUustalu22} [[Dylan McDermott]], [[Tarmo Uustalu]], *What Makes a Strong Monad?*, EPTCS **360** (2022) 113-133 [[arXiv:2207.00851](https://arxiv.org/abs/2207.00851), [doi:10.4204/EPTCS.360.6](https://doi.org/10.4204/EPTCS.360.6)]

A comparison of monads with [[applicative functors]] (also known as idioms)
and with [[arrows (in computer science)]] is in

* Exequiel Rivas, _Relating Idioms, Arrows and Monads from Monoidal Adjunctions_, ([arXiv:1807.04084](https://arxiv.org/abs/1807.04084))

### In quantum computation

Discussion of aspects of [[quantum computing]] in terms of monads:

* J. K. Vizzotto, [[Thorsten Altenkirch]], A. Sabry, *Structuring quantum effects: superoperators as arrows*, Mathematical Structures in Computer Science **16** 3 (2006)  453-468 [[arXiv:quant-ph/0501151](https://arxiv.org/abs/quant-ph/0501151), [doi:10.1017/S0960129506005287](https://doi.org/10.1017/S0960129506005287)]

  > ([[superoperators]] as [[arrows in computer science]])

The [[quantum IO monad]]:

* [[Thorsten Altenkirch]], [[Alexander Green]], *The quantum IO monad*, Ch. 5 of: Simon Gay, Ian Mackie (eds.): *Semantic Techniques in Quantum Computation* (2010) 173-205 [[pdf](http://www.cs.nott.ac.uk/~txa/publ/qio-chapter.pdf), [talk slides](http://www.cs.nott.ac.uk/~txa/talks/qnet06.pdf), [doi:10.1017/CBO9781139193313.006](https://doi.org/10.1017/CBO9781139193313.006)]

Exposition:

* [[Alexander Green]], *The Quantum IO Monad*, Nottingham  (2007) [[pdf](http://drinkupthyzider.co.uk/asg/pdfs/bctcs07.pdf), [[Green-QIOMonad.pdf:file]] ]

Implementation in [[Haskell]]:

* [[Alexander Green]], *[hackage.haskell.org/package/QIO](https://hackage.haskell.org/package/QIO)*

Much of the text and the diagrams in the entry above follow

* [[Hisham Sati]], [[Urs Schreiber]], *[[schreiber:The Quantum Monadology|The Quantum Monadology]]* [[arXiv:2310.15735](https://arxiv.org/abs/2310.15735)]

[[!redirects monad (computer science)]]
[[!redirects monads (computer science)]]

[[!redirects monad (in computer science)]]
[[!redirects monads (in computer science)]]

[[!redirects monad (in programming theory)]]
[[!redirects monads (in programming theory)]]

[[!redirects monad in computer science]]
[[!redirects monads in computer science]]

[[!redirects computational effect]]
[[!redirects computational effects]]

[[!redirects monadic effect]]
[[!redirects monadic effects]]

[[!redirects monadic computational effect]]
[[!redirects monadic computational effects]]

[[!redirects comonads in computer science]]

[[!redirects comonadic context]]
[[!redirects comonadic contexts]]

[[!redirects monadic bind operation]]
[[!redirects monadic bind operations]]

[[!redirects comonadic extend operation]]
[[!redirects comonadic extend operations]]

[[!redirects do-notation]]
[[!redirects do notation]]

[[!redirects codo-notation]]
[[!redirects codo notation]]


monad (in linguistics)

* table of contents
{: toc}

##Idea

A number of researchers have proposed that the [[category theory|category theoretic]] concept of [[monads]] may play a role in understanding semantic and pragmatic issues in the use of natural language.

>Side effects are to programming languages what pragmatics are to natural languages: they both study how expressions interact with the worlds of their users. It might then come as no surprise that phenomena such as anaphora, presupposition, deixis and conventional implicature yield a monadic description. ([Maršík Amblard 2016, p. 3](#MarAmb16))

## Examples

In overview papers ([Cohn-Gordon](#Cohn-Gordon), [Asudeh](#Asudeh)), it is proposed that the following topics are explained by specific monads:

1. Conventional implicature: the [[writer monad]]
1. Optional arguments: the [[maybe monad]]
1. Presupposition failure: the exception monad
1. Anaphora: the [[state monad]] and set monad
1. Perspective, opacity and intentionality: the [[reader monad]]
1. Conjunction fallacies: the [[Giry monad|probability monad]]
1. Quantifier Scope: the [[continuation monad]]
1. Focus: the pointed set monad
1. Interrogatives: the set monad
1. Performatives: the [[IO monad]]

In ([Burke 1](#Burke1)) it is claimed that hyperintensionality can be analysed via monads and applicatives, while in ([Burke 2](#Burke2)) cross-sentential intensional anaphora is modelled using [[continuation-passing style|continuations]].

## Related concepts

* [[monad (in computer science)]]
* [[dependent type theoretic methods in natural language semantics]]

##References

For a summary of uses, see

* {#Cohn-Gordon} Reuben Cohn-Gordon, _Monad Transformers for Natural Language: Combining Monads to Model Effect Interaction_, [pdf](https://reubencohngordon.com/docs/monads.pdf)

* {#Asudeh} [[Ash Asudeh]], _Monads: Some Linguistic Applications_, [pdf](http://www.sas.rochester.edu/lin/sites/asudeh/handouts/asudeh-se-lfg13.pdf)

* [[Gianluca Giorgolo]] and [[Ash Asudeh]], _Natural Language Semantics with Enriched Meanings_, [pdf](http://www.sas.rochester.edu/lin/sites/asudeh/pdf/esslli2015-course-notes.pdf)

These refer to:

* [[Gianluca Giorgolo]] and [[Ash Asudeh]], 2011. Multidimensional Semantics with Unidimensional Glue Logic. In Butt and King 2011, 236–256.
* [[Gianluca Giorgolo]] and [[Ash Asudeh]], 2012a. _$\langle M, \eta, \star \rangle$ Monads for Conventional Implicatures_. In Ana Aguilar Guevara, Anna Chernilovskaya, and Rick Nouwen, eds., Proceedings of Sinn und Bedeutung 16. MIT Working Papers in Linguistics.
* [[Gianluca Giorgolo]] and [[Ash Asudeh]], 2012b. _Missing Resources in a Resource-Sensitive Semantics._ In Miriam Butt and Tracy Holloway King, eds., Proceedings of the LFG12 Conference, 219–239. Stanford, CA: CSLI Publications.
* [[Gianluca Giorgolo]] and [[Ash Asudeh]], 2013a. _Monads as a Solution for Generalized Opacity._ Ms., University of Oxford.
* [[Gianluca Giorgolo]] and [[Ash Asudeh]], 2013b. _One Semiring to Rule Them All._ Ms., University of Oxford.
* [[Ash Asudeh]] and [[Gianluca Giorgolo]], 2016. _Perspectives._ Semantics and Pragmatics vol. 9, [doi](http://dx.doi.org/10.3765/sp.9.21).
* Shan, Chung-chieh. 2001. _Monads for Natural Language Semantics._ In Kristina Striegnitz, ed., Proceedings of the ESSLLI-2001 Student Session, 285–298. 13th European Summer School in Logic, Language and Information.
* Christina Unger, 2011. _Dynamic Semantics as Monadic Computation._ In Manabu Okumura, Daisuke Bekki, and Ken Satoh, eds., New Frontiers in Artificial Intelligence - JSAI-isAI 2011, 68–81.
* Simon Charlow, 2014. _On the semantics of exceptional scope_, New York University dissertation.

For work on hypertensionality, see:

*  {#Burke1} Luke Burke, _Monads for hyperintensionality? A situation semantics for hyperintensional side effects and intra-sentential anaphora
_, [pdf](https://www.aclweb.org/anthology/W19-1104.pdf)

*  {#Burke2} Luke Burke, _P-HYPE: A monadic situation semantics for hyperintensional side effects_, [pdf](https://semanticsarchive.net/Archive/Tg3ZGI2M/Burke.pdf)

For the specific use of [[continuation-passing style]] techniques, see

* Chris Barker, Chung-Chieh Shan, _Continuations and Natural Language_, OUP, 2014, ([introduction](https://www.nyu.edu/projects/barker/barker-shan-continuations-book-intro.pdf))
* Chris Barker, _Continuations and the nature of quantification_, Natural Language Semantics, 10(3):211–242, 2002.
*  Chris Barker, _Continuations in natural language_, in Hayo Thielecke, editor, Proceedings of the Fourth ACM SIGPLAN Continuations Workshop (CW'04), Birmingham, UK, 2004.
* Ekaterina Lebedeva, _Expression de la dynamique du discours à l'aide de continuations_, ([thesis](http://www.theses.fr/2012LORR0025))

The alternative approach to treating [[side effects]], known as [[algebraic effects]], has also been employed in natural language semantics:

* Jirka Maršík, Maxime Amblard, _Algebraic Effects and Handlers in Natural Language Interpretation_, [pdf](https://hal.archives-ouvertes.fr/hal-01079206/file/effects-paper.pdf)
* {#MarAmb16} Jirka Maršík, Maxime Amblard, _Introducing a Calculus of Effects and Handlers for Natural Language Semantics_, [arXiv:1606.06125](https://arxiv.org/abs/1606.06125)

The weaker notion of [[applicative functors]] has also been used:

* Oleg Kiselyov, _Applicative Abstract Categorial Grammars_, ([pdf](http://okmij.org/ftp/gengo/applicative-symantics/AACG.pdf))
* Oleg Kiselyov, _Applicative Abstract Categorial Grammars in Full Swing_, ([pdf](http://okmij.org/ftp/gengo/applicative-symantics/AACG1.pdf))
* Simon Charlow, _A modular theory of pronouns and binding_, ([pdf](http://ling.auf.net/lingbuzz/003720))


monad in algebraic geometry

In [[algebraic geometry]] the local model is an [[affine scheme]]: affine schemes are glued in various topologies like Zariski and flat to obtain [[algebraic schemes]], [[algebraic space]]s and so on.

Grothendieck emphasised the [[relative point of view]]: the main foundational effort should be devoted to the study of properties of morphisms rather than spaces. Thus one can consider an [[affine morphism]] instead of an affine scheme; affine morphism $f: X\to S$ can be considered as a relative affine scheme over $S$, intuitively a bundle of affine schemes. If $S$ is itself an affine scheme, corresponding to a ring $R_S$ and $f$ is affine then $f$ is the opposite of a morphism $f^\circ : R_S\to R_X$ where $X = Spec R_X$.

By the [[Gabriel-Rosenberg theorem]] a scheme can be reconstructed from the category of quasicoherent sheaves over a scheme. Thus one is tempted to replace the properties of morphisms by properties of the "geometric functors" among the corresponding categories of quasicoherent sheaves. The properties of affine morphisms were first elucidated in [[Jean-Pierre Serre|Serre]]'s criterium of affineness. It appears that the direct image functor $f_* : Qcoh_S\to Qcoh_X$ of an affine morphism $f:X\to S$ is faithful and having its own right adjoint $f^!$. The adjunction $f^*\dashv f_*$ induces a monad making $Qcoh_X$ monadic over $Qcoh_S$. If $S$ were just $Spec \mathbb{Z}$ then this is clear as then $X = Spec R_X$ and $Qcoh_X = {}_R Mod$.

category: algebraic geometry, noncommutative geometry


monad in nonstandard analysis > history

< [[monad in nonstandard analysis]]


monad retromorphism

+-- {: .rightHandSide}
+-- {: .toc .clickDown tabindex="0"}
###Context###
#### Categorical algebra
+-- {: .hide}
[[!include categorical algebra -- contents]]
=--
#### 2-Category theory
+--{: .hide}
[[!include 2-category theory - contents]]
=--
=--
=--

#Contents#
* table of contents
{:toc}

## Idea

A **retromorphism** of [[monads]] is a [[retrocell]] between the carriers of the monads, which preserves the unit and multiplication.

## Examples

* A monad internal to the [[double category]] $Span$ is a [[small category]]. A monad retromorphism is then a [[retrofunctor]].

## References

The terminology is introduced in the following thesis, where the definition is alluded to:

* [[Matthew Di Meglio]], _The category of asymmetric lenses and its proxy pullbacks_. Master’s thesis. Macquarie University, 2021. doi: 10.25949/20236449, [pdf](https://mdimeglio.github.io/papers/The_category_of_asymmetric_lenses_and_its_proxy_pullbacks.pdf)

A definition is introduced in:

* {#Clarke2022} [[Bryce Clarke]], _The double category of lenses_, PhD thesis, Macquarie University, 2022. ([doi:10.25949/22045073.v1](https://doi.org/10.25949/22045073.v1))

Monad retromorphisms are further studied in:

* [[Robert Paré]], _Retrocells_, [arXiv:2306.06436](https://arxiv.org/abs/2306.06436)

[[!redirects monad retromorphisms]]


monad transformation

+-- {: .rightHandSide}
+-- {: .toc .clickDown tabindex="0"}
### Context
#### Categorical algebra
+-- {: .hide}
[[!include categorical algebra -- contents]]
=--
=--
=--

#Contents#
* table of contents
{:toc}

## Idea

The following terminology for the ([[higher morphism|higher]]) [[morphisms]] in the [2-category of monads](monad#BicategoryOfMonads) have appeared in the literature or are otherwise sensible:

| author(s) | [[1-morphisms]] | [[2-morphisms]] |
|---------|-----------------|-----------------|
| [Maranda 1966](#Maranda66), [1968](#Maranda68),
 [Frei 1969](#Frei69),
[Pumplün 1970](#Pumplün70),
 [Borceux 1994](#Borceux94) | "morphisms of monads" | ---  |
| [Street 1972](#Street72) | "monad functors" | "monad functor transformations" |
| [Moggi 1989](#Moggi89) | "monad-morphisms" | --- |
| [Espinosa 1995](#Espinosa95),
 [Liang, Hudak & Jones 1995](#LiangHudakJones95) | "[[monad transformers]]" ${}^1$ | ---
| [Lack & Street 2002](#LackStreet02) | "monad morphisms" | "monad transformations" |
| --- | "monad [[1-morphisms]]" | "monad [[2-morphisms]]" |
| --- | "[[lax natural transformation|lax transformations]]" of monads | "[[modifications]]" of monads |

${}^1$: Notice here that the "[[monad transformers]]" in [Espinosa 1995](#Espinosa95), [Liang, Hudak & Jones 1995](#LiangHudakJones95) (as commonly understood now in [[Haskell]]) are indeed 1-morphisms of monads, but understood with additional structure, namely appearing in [[natural transformation|natural]] families constituting a [[pointed endofunctor]] on the category of monads (made explicit in [Winitzki 2022 p. 474](#Winitzki22)).

Of course, monads are often referred to via their [[underlying]] [[functors]], the morphisms between which are, of course, commonly known as *transformations*, too: [[natural transformations]]. Therefore (for the usual monads in [[Cat|$Cat$]]) monad morphisms are, in any case, *natural transformation of functors, respecting their monad structure*.

Similarly, if one thinks of monads as [[lax functors]] $\ast \to Cat$ (which is where they get their name from!, see [here](monad#Etymology)) then their 1-morphisms are by default to be called *[[lax natural transformations]]* (and their 2-morphisms *[[modifications]]*).

## Related entries

* [[monad transformer]]

* [[transformation of adjoints]]

## References

* {#Maranda66} [[Jean-Marie Maranda]], *On Fundamental Constructions and Adjoint Functors*, Canadian Mathematical Bulletin **9** 5  (1966) 581-591 [[doi:10.4153/CMB-1966-072-9](https://doi.org/10.4153/CMB-1966-072-9)]

* {#Maranda68} [[Jean-Marie Maranda]], *Sur les Proprietes Universelles des Foncteurs Adjoints*,  In: *Études sur les Groupes abéliens* / *Studies on Abelian Groups* Springer (1968) [[doi:10.1007/978-3-642-46146-0_16](https://doi.org/10.1007/978-3-642-46146-0_16)]

* {#Frei69} [[Armin Frei]], *Some remarks on triples*, Mathematische Zeitschrift **109** (1969) 269–272 [[doi:10.1007/BF01110118](https://doi.org/10.1007/BF01110118)]

* {#Pumplün70} [[Dieter Pumplün]], *Eine Bemerkung über Monaden und adjungierte Funktoren*, Mathematische Annalen **185** (1970) 329-337 [[eudml:161964](https://eudml.org/doc/161964), [[Pumpluen-Monaden.pdf:file]]]

* {#Street72} [[Ross Street]], *The formal theory of monads*, Journal of Pure and Applied Algebra **2** 2 (1972) 149-168 [doi:10.1016/0022-4049(72)90019-9]

* {#Moggi89} [[Eugenio Moggi]], *An abstract View of Programming Languages*, LFCS report ECS-LFCS-90-113 (1989) [[web](http://www.lfcs.inf.ed.ac.uk/reports/90/ECS-LFCS-90-113), [[Moggi-AbstractView.pdf:file]]]

* {#Borceux94} [[Francis Borceux]], Def. 4.5.8 in: *[[Handbook of Categorical Algebra]]*, Vol. 2: *Categories and Structures*, Encyclopedia of Mathematics and its Applications **50** Cambridge University Press (1994) [[doi:10.1017/CBO9780511525865](https://doi.org/10.1017/CBO9780511525865)]

* {#Espinosa94} [[David A. Espinosa]], *Building Interpreters by Transforming Stratified Monads* (1994) [[pdf](https://github.com/davidespinosa01/papers/blob/master/E/Espinosa%20David/espinosa-stratified-monads.pdf), [[Espinosa-StratifiedMonads.pdf:file]]]

* {#Espinosa95} [[David A. Espinosa]], *Semantic Lego*, PhD thesis, Columbia University (1995) [[pdf](https://github.com/davidespinosa01/papers/blob/master/E/Espinosa%20David/espinosa-stratified-monads.pdf), [[Espinosa-SemanticLego.pdf:file]], slides:[pdf](https://github.com/davidespinosa01/papers/blob/346c2ded6af78805701106d51daee8f7a756c948/E/Espinosa%20David/espinosa-thesis-slides.pdf), [[Espinosa-SemanticLego-slides.pdf:file]]]

* {#LiangHudakJones95} Sheng Liang, [[Paul Hudak]], [[Mark Jones]], *Monad transformers and modular interpreters*, POPL '95 (1995) 333–343 [[doi:10.1145/199448.199528](https://doi.org/10.1145/199448.199528)]

* {#LackStreet02} [[Stephen Lack]], [[Ross Street]], *The formal theory of monads II*, Journal of Pure and Applied Algebra **175** 1–3 (2002) 243-265 [doi:10.1016/S0022-4049(02)00137-8]

* {#Winitzki22} [[Sergei Winitzki]], Section 14 of: *The Science of Functional Programming -- A tutorial, with examples in Scala* (2022) [[leanpub:sofp](https://leanpub.com/sofp), [github:sofp](https://github.com/winitzki/sofp)]

[[!redirects monad transformations]]

[[!redirects monad morphism]]
[[!redirects monad morphisms]]

category: disambiguation


monad transformer

+-- {: .rightHandSide}
+-- {: .toc .clickDown tabindex="0"}
###Context###
#### Categorical algebra
+-- {: .hide}
[[!include categorical algebra -- contents]]
=--
#### Type theory
+-- {: .hide}
[[!include type theory - contents]]
=--
=--
=--

#Contents#
* table of contents
{:toc}

## Idea
 {#Idea}

In [[functional programming]] using [[monads (in computer science)|monads for computational effects]], *monad transformers* [[Espinosa 1994 §4](#Espinosa94), [1995 §2.6](#Espinosa95)] are type constructors which take one monad to another in a compatible way.

In practice this is typically motivated by and used for *combining* a monadic effect $\mathcal{E}_{new}$ into any given one $\mathcal{E}$ by $\mathcal{E} \mapsto \mathcal{E}_{new} \circ \mathcal{E} $ via a universal [[distributive law]].

Formally, a monad transformer on a given category $\mathbf{C}$ (of [[data types|data]] [[types]]) is a [[pointed endofunctor]] on the [category of monads](monad#TransformationOfMonadsOnFixedCategory) $Mnd(\mathbf{C})$ (this is made explicit in [Winitzki 2022, p. 474](#Winitzki22)), namely:

1. an [[endofunctor]] $\mathcal{E} \mapsto \mathcal{E}'$ taking monads to monads

1. for each $\mathcal{E}$ a [morphism of monads](monad#TransformationOfMonadsOnFixedCategory) $trans_{\mathcal{E}} \,\colon\, \mathcal{E} \longrightarrow \mathcal{E}'$ (a *[[monad transformation]]*)

1. such that these are [[natural transformations|natural]] with respect to [morphism of monads](monad#TransformationOfMonadsOnFixedCategory).

This construction is sometimes viewed (see [HP07](#HP07), and at *[[Eff]]*) as a complication resulting from passing to monads from the setting of [[Lawvere theories]], where any two theories may be naturally combined.

## Details
 {#Details}

The following Def. \ref{MonadTransformer} is essentially the notion in [Liang, Hudak & Jones 1995, left column of p. 339 ](#LiangHudakJones95), as now commonly used in [[Haskell]] (see the *[Haskell Transformer class](https://hackage.haskell.org/package/transformers-0.5.6.2/docs/Control-Monad-Trans-Class.html#g:1)*).

\begin{remark}
\label{PointedEndofunctorConditionOrNot}
These authors, and the [[functional programming]]/[[Haskell]]-community following them, insist that "$trans_{(\text{-})}$" (eq:UnderlyingNaturalTransformation) --- which they denote "$lift \text{-}$" ---  is not just a transformation between a single pair of monads, but a component a [[pointed endofunctor]] on the whole category of monads. This further condition may be considered (or not) in addition to the following discussion.
\end{remark}

\begin{definition}
\label{MonadTransformer}
  Given monads $\mathcal{E}$, $\mathcal{E}'$ on the same [[category]] $\mathbf{C}$, a *monad transformer* between them is:

* a system of [[morphisms]]

  \[
     \label{UnderlyingNaturalTransformation}
     D \,\colon\, Type
     \;\;\;\;\;\;
     \vdash
     \;\;\;\;\;\;
     trans_D
       \,\colon\,
     \mathcal{E}(D) \to \mathcal{E}'(D)
  \]

which

1. preserves the return-operations, in that

   \[
     \label{RespectForReturnOperation}
     trans \circ ret^{\mathcal{E}}
     \;=\;
     ret^{\mathcal{E}'}
     \,,
   \]

1. preserves the bind-operations, in that for
   $prog_{12}\,\colon\, D_1 \to \mathcal{E}(D_2)$
   and
   $prog_{23}\,\colon\, D_2 \to \mathcal{E}(D_3)$

   we have

   \[
     \label{RespectForBindOperation}
     trans_{D_3}
     \circ
     \Big(
       \big( bind^{\mathcal{E}} prog_{23} \big)
       \circ
       prog_{12}
     \Big)
     \;\;=\;\;
     bind^{\mathcal{E}'}
     \Big(
       \big(
         trans_{D_3} \circ prog_{23}
       \big)
     \Big)
     \circ
     \big(
       trans_{D_2} \circ prog_{12}
     \big)
     \mathrlap{\,.}
   \]

\end{definition}

In [Schrijvers, Piróg, Wu & Jaskelioff 2019 p. 99](#SchrijversPirógWuJaskelioff19) the analogous condition is stated in terms of the join-operation. We may check that these are equivalent:

\begin{proposition}
\label{EquivalenceOfDefinitions}
  A system of transformations $trans_D \,\colon\, \mathcal{E}(D) \to \mathcal{E}'(D)$ is a monad transformer in the sense of Def. \ref{MonadTransformer} (cf. Rem. \ref{PointedEndofunctorConditionOrNot}) iff it is a [homomorphism of monads](monad#TransformationOfMonadsOnFixedCategory) (in the original sense of [Maranda 1966](monad#Maranda66)), i.e.:

1. a [[natural transformation]] $\trans \,\colon\, \mathcal{E} \to \mathcal{E}'$ of the [[underlying]] [[functors]],

1. respecting the [[unit of a monad|unit/return-operation]], in that the following [[commuting diagram|diagrams commute]]:

   \[
     \label{RespectForTheUnit}
     \array{
       D
         &\overset{ret^{\mathcal{E}}_D}{\longrightarrow}&
       \mathcal{E}(D)
       \\
       \mathllap{{}^{id}}\Big\downarrow
         &&
       \Big\downarrow\mathrlap{{}^{trans_D}}
       \\
       D
         &\underset{ret^{\mathcal{E}'}_D}{\longrightarrow}&
       \mathcal{E}'(D)
     }
   \]

1. respecting the join-operation (the "monad multiplication"), in that it makes the following [[commuting diagram|diagram commute]]:

\begin{tikzcd}[sep=large]
  \mathcal{E}\big(\mathcal{E}(\mbox{-})\big)
  \ar[
     rr,
     "{
       \mathrm{trans}_{{}_{\mathcal{E}(\mbox{-})}}
     }"{description}
  ]
  \ar[
    dd,
    "{
      \mathrm{join}^{\mathcal{E}}_{(\mbox{-})}
    }"{description}
  ]
  &&
  \mathcal{E}'\big(\mathcal{E}(\text{-})\big)
  \ar[
    rr,
    "{
      \mathcal{E}'(\mathrm{trans}_{(\mbox{-})})
    }"{description}
  ]
  &&
  \mathcal{E}'\big(\mathcal{E}'(\text{-})\big)
  \ar[
    dd,
    "{
      \mathrm{join}^{\mathcal{E}'}_{(\mbox{-})}
    }"{description}
  ]
  \\
  \\
  \mathcal{E}(\mbox{-})
  \ar[
    rrrr,
    "{
       \mathrm{trans}_{(\mbox{-})}
    }"{description}
  ]
  &&&&
  \mathcal{E}'(\mbox{-})
\end{tikzcd}

\end{proposition}
\begin{proof}
Recall that the relation between the bind- and join-operations is:

\[
  \label{BindFromJoin}
  bind^{\mathcal{E}} \big( f \,\colon\, D_1 \to \mathcal{E}(D_2) \big)
  \;\equiv\;
  join^{\mathcal{E}}_{D_2} \circ \mathcal{E}(f)
\]

and

\[
  \label{FunctorFromBind}
 \mathcal{E}(f \,\colon\, D_1 \to D_2)
 \;\equiv\;
 bind^{\mathcal{E}}
 \big(
   D_1
     \xrightarrow{\; f \;}
   D_2
     \xrightarrow{\; ret^{\mathcal{E}}_{D_2} \;}
   \mathcal{E}(D_2)
 \big)
\]

\[
  \label{JoinFromBind}
  join^{\mathcal{E}}_{D}
  \;\equiv\;
  bind^{\mathcal{E}}\big( id_{\mathcal{E}(D)} \big)
  \,.
\]

Now in one direction:
Given a [morphism of monads](monad#TransformationOfMonadsOnFixedCategory) $trans \,\colon\, \mathcal{E} \to \mathcal{E}'$,
then consider the [[pasting diagram]] of the above square with the [[naturality square]] of $trans$ as follows:

\begin{tikzcd}[sep=large]
  D_1
  \ar[
    rr,
    "{
      \mathrm{prog}_{12}
    }"{description}
  ]
  &&
  \mathcal{E}(D_2)
  \ar[
     rr,
     "{
       \mathrm{trans}_{D_2}
     }"{description}
  ]
  \ar[
    dd,
    "{
      \mathcal{E}(\mathrm{prog}_{23})
    }"{description}
  ]
  &&
  \mathcal{E}'(D_2)
  \ar[
    dd,
    "{
      \mathcal{E}'(\mathrm{prog}_{23})
    }"{description}
  ]
  \\
  \\
  &&
  \mathcal{E}\big(\mathcal{E}(D_3)\big)
  \ar[
     rr,
     "{
       \mathrm{trans}_{{}_{\mathcal{E}(D_3)}}
     }"{description}
  ]
  \ar[
    dd,
    "{
      \mathrm{join}^{\mathcal{E}}_{D_3}
    }"{description}
  ]
  &&
  \mathcal{E}'\big(\mathcal{E}(D_3)\big)
  \ar[
    rr,
    "{
      \mathcal{E}'(\mathrm{trans}_{D_3})
    }"{description}
  ]
  &&
  \mathcal{E}'\big(\mathcal{E}'(D_3)\big)
  \ar[
    dd,
    "{
      \mathrm{join}^{\mathcal{E}'}_{D_3}
    }"{description}
  ]
  \\
  \\
  &&
  \mathcal{E}(D_3)
  \ar[
    rrrr,
    "{
       \mathrm{trans}_{D_3}
    }"{description}
  ]
  &&&&
  \mathcal{E}'(D_3)
\end{tikzcd}

Going diagonally through this [[commuting diagram]] and using (eq:BindFromJoin): The total left and bottom composite is the left hand side of (eq:RespectForBindOperation) and the total top and right composite is the right hand side of (eq:RespectForBindOperation), thus proving their equality.

In the other direction, if (eq:RespectForBindOperation) holds then its restriction to the case $prog_{12} \,\equiv\, id \,\equiv\, prog_{23}$ immediately yields, by (eq:JoinFromBind), the above commtuting diagram expressing respect for the join.

{#NaturalityFollows} It just remains to see that the system of transformations $trans_{(\text{-})}$ (eq:UnderlyingNaturalTransformation) is necessarily [[natural transformation|natural]]. This is shown by the following sequence of equalities, for $prog \,\colon\, D_1 \to D_2$:

$$
  \begin{array}{ll}
    trans_{D_2}  \circ \mathcal{E}(prog)
    \\
    \;=\;
    trans_{D_2}
    \circ
    bind^{\mathcal{E}}\big(
      D_1
        \xrightarrow{ prog }
      D_2
        \xrightarrow{ ret^{\mathcal{E}}_D }
      \mathcal{E}(D_2)
    \big)
    \\
    \;=\;
    bind^{\mathcal{E}'}\big(
      D_1
        \xrightarrow{ prog }
      D_2
        \xrightarrow{ ret^{\mathcal{E}}_D }
      \mathcal{E}(D_2)
        \xrightarrow{ trans_{D_2} }
      \mathcal{E}'(D_2)
    \big)
    \circ
    trans_{D_1}
    \\
    \;=\;
    bind^{\mathcal{E}'}\big(
      D_1
        \xrightarrow{ prog }
      D_2
        \xrightarrow{ ret^{\mathcal{E}'}_D }
      \mathcal{E}'(D_2)
    \big)
    \circ
    trans_{D_1}
    \\
    \;=\;
    \mathcal{E}'(prog)
    \circ
    trans_{D_1}
    \mathrlap{\,,}
  \end{array}
$$

where we used, in order of appearance: (eq:FunctorFromBind), (eq:RespectForBindOperation), (eq:RespectForTheUnit) and finally (eq:FunctorFromBind) again.
\end{proof}

\begin{remark}
\label{MonadTransformationsActCovariantlyOnKleisliCategories}
**(monad transformations act covariantly on Kleisli categories)**
\linebreak
  The conditions (eq:RespectForReturnOperation) and (eq:RespectForBindOperation) equivalently say that the monad transformation $trans$ (eq:UnderlyingNaturalTransformation) induces a functor between the respective [[Kleisli categories]]

  \begin{tikzcd}[
    row sep=2pt
  ]
    &
    \mathbf{C}
    \ar[
      dl,
      end anchor={[yshift=2pt]},
      "{ F_{\mathcal{E}} }"{swap}
    ]
    \ar[
      dr,
      end anchor={[yshift=4pt]},
      "{ F_{\mathcal{E}'} }"
    ]
    \\
    \mathbf{C}_{\mathcal{E}}
    \ar[
      rr
    ]
    &&
    \mathbf{C}_{\mathcal{E}'}
    \\
    \mathcal{E}(D_1)
    \xrightarrow{ \phi }
    \mathcal{E}(D_2)
    &\mapsto&
    \mathrm{bind}
      ^{ \mathcal{E}' }
    \bigg(
    D_1
    \xrightarrow{
      \mathrm{ret}
        ^{ \mathcal{E} }
        _{ D_1 }
    }
    \mathcal{E}(D_1)
    \xrightarrow{ \phi }
    \mathcal{E}(D_2)
    \xrightarrow{
      \mathrm{trans}
        _{ D_2 }
    }
    \mathcal{E}'(D_2)
    \bigg)
    \,.
  \end{tikzcd}

As shown, this respects the [free-module](algebra+over+a+monad#FreeAlgebras) functors

\begin{tikzcd}[
  row sep=5, column sep=10
]
  \mathbf{C}
  \ar[rr, "{ F_{\mathcal{E}} }"]
  &&
  \mathbf{C}_{\mathcal{E}}
  \\
  D_1 \xrightarrow{f} D_2
  &\mapsto&
  \mathcal{E}(D_1) \xrightarrow{ \mathcal{E}(f) }
  \mathcal{E}(D_2)
\end{tikzcd}

because the following [[pasting diagram]] [[commuting diagram|commutes]] (the left square by (eq:RespectForReturnOperation), the right square by [[natural transformation|naturality]], see [above](#NaturalityFollows)):

\begin{tikzcd}[sep=20pt]
    D_1
    \ar[
      rr,
      "{
        \mathrm{ret}
          ^{ \mathcal{E} }
          _{ D_1 }
      }"
    ]
    \ar[dd, equals]
    &&
    \mathcal{E}(D_1)
    \ar[
      rr,
      "{ \mathcal{E}(f) }"
    ]
    \ar[
      dd,
      "{ \mathrm{trans}_{D_1} }"{description}
    ]
    &&
    \mathcal{E}(D_2)
    \ar[
      dd,
      "{
        \mathrm{trans}
          _{ D_2 }
      }"{description}
    ]
    \\
    \\
    D_1
    \ar[
      rr,
      "{
        \mathrm{ret}
          ^{ \mathcal{E}' }
          _{ D_1 }
      }"
    ]
    &&
    \mathcal{E}'(D_1)
    \ar[
      rr,
      "{ \mathcal{E}'(f) }"
    ]
    &&
    \mathcal{E}'(D_2)
\end{tikzcd}

Since it is evident that composite monad transformations give composite such functors, this means that assigning [[Kleisli categories]] to [[monads]] on $\mathbf{C}$ extends to a [[functor]] of the form:

\begin{tikzcd}[sep=0pt]
  \mathrm{Mnd}(\mathbf{C})
  \ar[
     rr
  ]
  &&
  \mathrm{Cat}^{\mathbf{C}/}
  \\
  \mathcal{E} &\mapsto& \mathbf{C}_{\mathcal{E}}
\end{tikzcd}

This is probably the functor alluded to in [Linton 1969, Lem. 10.2](monad#Linton69).
\end{remark}

## Related concepts

* [[monad transformation]]

## References

Original discussion:

* {#Espinosa94} [[David A. Espinosa]], §3.2 in: *Building Interpreters by Transforming Stratified Monads* (1994) [[pdf](https://github.com/davidespinosa01/papers/blob/master/E/Espinosa%20David/espinosa-stratified-monads.pdf), [[Espinosa-StratifiedMonads.pdf:file]]]

* {#Espinosa95} [[David A. Espinosa]], §2.6 in: *Semantic Lego*, PhD thesis, Columbia University (1995) [[pdf](https://github.com/davidespinosa01/papers/blob/master/E/Espinosa%20David/espinosa-stratified-monads.pdf), [[Espinosa-SemanticLego.pdf:file]], slides:[pdf](https://github.com/davidespinosa01/papers/blob/346c2ded6af78805701106d51daee8f7a756c948/E/Espinosa%20David/espinosa-thesis-slides.pdf), [[Espinosa-SemanticLego-slides.pdf:file]]]

* {#LiangHudakJones95} Sheng Liang, [[Paul Hudak]], [[Mark Jones]], *Monad transformers and modular interpreters*, POPL '95 (1995) 333–343 [[doi:10.1145/199448.199528](https://doi.org/10.1145/199448.199528)]

* {#SchrijversPirógWuJaskelioff19} Tom Schrijvers, Maciej Piróg, Nicolas Wu, Mauro Jaskelioff: *Monad transformers and modular algebraic effects: what binds them together*, in: *Haskell 2019: Proceedings of the 12th ACM SIGPLAN International Symposium on Haskell* (2019) 98–113 [[doi:10.1145/3331545.3342595](https://doi.org/10.1145/3331545.3342595)]

Textbook account:

* {#Winitzki22} [[Sergei Winitzki]], Section 14 of: *The Science of Functional Programming -- A tutorial, with examples in Scala* (2022) [[leanpub:sofp](https://leanpub.com/sofp), [github:sofp](https://github.com/winitzki/sofp)]

See also:

* Wikipedia, *[Monad transformer](https://en.wikipedia.org/wiki/Monad_transformer)*

* Haskell, *[Monad transformers](https://en.wikibooks.org/wiki/Haskell/Monad_transformers)*

* [hackage.haskell.org/package/transformers-0.5.6.2/docs/Control-Monad-Trans-Class.html](https://hackage.haskell.org/package/transformers-0.5.6.2/docs/Control-Monad-Trans-Class.html)

* Bryan O'Sullivan, Don Stewart, and John Goerzen, _Monad transformers_, [Chapter 18](http://book.realworldhaskell.org/read/monad-transformers.html) of *Real World Haskell*

* [[Mauro Jaskelioff]], [[Eugenio Moggi]], *Monad Transformers as Monoid Transformers*, Theoretical Computer Science **411** 51–52 (2010) 4441-4466 [[doi:10.1016/j.tcs.2010.09.011](https://doi.org/10.1016/j.tcs.2010.09.011), [pdf](http://www.disi.unige.it/person/MoggiE/ftp/tcs10.pdf)]

* {#HP07} [[Martin Hyland]], [[John Power]], _The Category Theoretic Understanding of Universal Algebra: Lawvere Theories and Monads_, Electronic Notes in Theoretical Computer Science (ENTCS) **172** (2007) 437-458  [[pdf](https://www.dpmms.cam.ac.uk/~martin/Research/Publications/2007/hp07.pdf)]

* Mauro Jaskelioff, *Monatron: An Extensible Monad Transformer Library*, in: *Implementation and Application of Functional Languages. IFL 2008*, Lecture Notes in Computer Science **5836** (2011) 233–248 [[doi:10.1007/978-3-642-24452-0_13](https://doi.org/10.1007/978-3-642-24452-0_13)]

* Oleksandr Manzyuk, _Calculating monad transformers with category theory_ (2012) [[pdf](https://oleksandrmanzyuk.files.wordpress.com/2012/02/calc-mts-with-cat-th1.pdf)]

* [[Maciej Piróg]], *Eilenberg--Moore Monoids and Backtracking Monad Transformers*, EPTCS **207** (2016) 23-56 [[ar](https://arxiv.org/abs/1604.01184), [doi:10.4204/EPTCS.207.2](https://doi.org/10.4204/EPTCS.207.2)&rbrack

* Chung-Chieh Shan, _Monad transformers_ (2020) [[blog post](http://conway.rutgers.edu/~ccshan/wiki/blog/posts/Monad_transformers/)]

[[!redirects monad transformers]]


monad with arities

+-- {: .rightHandSide}
+-- {: .toc .clickDown tabindex="0"}
###Context###
#### Algebra
+--{: .hide}
[[!include higher algebra - contents]]
=--
#### 2-Category theory
+--{: .hide}
[[!include 2-category theory - contents]]
=--
=--
=--

#Contents#
* table of contents
{:toc}

## Idea

A _monad with arities_ is a [[monad]] that admits a generalized [[nerve]] construction. This allows us to view its [[algebra over a monad|algebras]] as [[presheaves]]-with-[[properties]] in a canonical way.

This generalized nerve construction also generalizes the construction of the [[syntactic category]] of a [[Lawvere theory]].

Monads with arities are subsumed by [[relative monads]].

##Definition##

Let $\mathcal{C}$ be a [[category]], and $i_A : \mathcal{A} \subset \mathcal{C}$ a [[subcategory]]. As explained at [[dense functor]], for any [[object]] $X$ of $\mathcal{C}$, there is a canonical [[cocone]] over the [[forgetful functor]] $(\mathcal{A} \downarrow X) \to \mathcal{C}$, which we call the **canonical $\mathcal{A}$-cocone at $X$**. The subcategory $\mathcal{A} \subset \mathcal{C}$ is called _dense_ if this cocone is [[colimit|colimiting]] for every object $X$ of $C$.

 If $\mathcal{C}$ be a category and $i_A : \mathcal{A} \subset \mathcal{C}$ is a dense subcategory, then the **$\mathcal{A}$-[[nerve|nerve functor]]** is given by

\[
  \begin{aligned}
     \nu_{\mathcal{A}} : \mathcal{C}
       &\to [\mathcal{A}^{op}, \mathrm{Set}]
     \\
     X &\mapsto \mathcal{C}(i_A, X)
   \end{aligned}
 \,.
\]

A [[monad]] $(T,\mu,\eta)$ on $\mathcal{C}$ is said to **have arities $\mathcal{A}$** if $\nu_{\mathcal{A}} \circ T$ sends canonical $\mathcal{A}$-cocones to [[colimit|colimiting cocones]].

##Nerve Theorem##
 {#NerveTheorem}

The nerve theorem consists of two statements:

**I.** If $\mathcal{A}$ is dense in $\mathcal{C}$ and if $T$ is a monad with arities $\mathcal{A}$ on $\mathcal{C}$, then $\mathcal{C}^T$ has a dense subcategory $\Theta_T$ given by the [[free functor|free]] $T$-[[algebra over a monad|algebras]] on objects of $\mathcal{A}$.

By definition of density, this means that the nerve functor $\nu_{\Theta_T} : \mathcal{C}^T \to [\Theta_T^{op}, \mathrm{Set}]$ is [[full and faithful functor|full and faithful]]. This allows us to view $T$-algebras as [[presheaves]] (on $\Theta_T$) with a certain [[stuff, structure, property|property]]. The second part of the nerve theorem tells us what this property is.

**II.** Let $j: \mathcal{A} \to \Theta_T$ be the restricted free algebra functor. A presheaf $P : \Theta_T^{op} \to \mathrm{Set}$ is in the essential image of $\nu_{\Theta}$ if and only if the restriction along $j$,
\[ P\circ j : A^{op} \to \Set \]
 is in the essential image of $\nu_A$.

The proof of the nerve theorem, following [BMW](#BMW), is fairly straightforward.  Consider the adjunction $j_! : [\mathcal{A}^{op},Set] \rightleftarrows [\Theta_T^{op},Set] : j^*$ given by restriction and [[left Kan extension]].  The assumption that $T$ has arities $\mathcal{A}$ can be reformulated to say that the nerve $\nu_{\mathcal{A}} : \mathcal{C} \to  [\mathcal{A}^{op},Set]$ is a strong [[monad morphism]] from $T$ to $j^* j_!$, i.e. there is a coherent isomorphism $\nu_{\mathcal{A}} T \cong j^* j_! \nu_{\mathcal{A}}$.  Since $\nu_{\mathcal{A}}$ is fully faithful, this means that if we identify $\mathcal{C}$ with the image of $\nu_{\mathcal{A}}$, then the monad $T$ gets identified with $j^* j_!$.  But the adjunction $j_! \dashv j^*$ is also monadic (since $j$ is bijective on objects), so the category of $T$-algebras gets identified with the full subcategory of $j^* j_!$-algebras, i.e. presheaves on $\Theta_T$, whose underlying presheaf on $\mathcal{A}$ is in the image of $\nu_{\mathcal{A}}$.  This is exactly the two statements of the nerve theorem.

##Examples##

* Every [[p.r.a. monad]] has arities.  In particular, therefore, every [[polynomial monad]] has arities.

* The free [[groupoid]] monad on the category of [[directed graphs]] with [[involution]] has arities, although it is not p.r.a.

See [BMW](#BMW) for more.

## Related pages

* A monad with arities is equivalently an internal [[monad]] in the [[2-category]] of [[categories with arities]].

* A monad with arities $i_A$ is equivalent to an $i_A$-[[relative monad]].

##References##

See the discussion at

* [[Tom Leinster]], _How I learned to love the nerve construction_ (2008) ([blog](http://golem.ph.utexas.edu/category/2008/01/mark_weber_on_nerves_of_catego.html))

The associated paper is

* [[Mark Weber]], _Familial 2-functors and parametric right adjoints_ (2007) ([tac](http://www.tac.mta.ca/tac/volumes/18/22/18-22abs.html))

These ideas are clarified and expanded on in

* [[Paul-André Melliès]]. _Segal condition meets computational effects._ (2010, 25th Annual IEEE Symposium on Logic in Computer Science).

* {#BMW} [[Clemens Berger]], [[Paul-André Melliès]], [[Mark Weber]], _Monads with Arities and their Associated Theories_ (2011) ([arXiv:1101.3064](http://arxiv.org/abs/1101.3064))

On the connection between [[relative monads]] and monads with arities:

* {#ACU14} [[Thorsten Altenkirch]], [[James Chapman]], [[Tarmo Uustalu]], *Monads need not be endofunctors*, Logical Methods in Computer Science **11** 1:3 (2015) 1–40 [[arXiv:1412.7148](https://arxiv.org/abs/1412.7148), [pdf](http://www.cs.nott.ac.uk/~txa/publ/jrelmon.pdf), doi:10.2168/LMCS-11(1:3)2015]

[[!redirects monads with arities]]


monadic > history

< [[monadic]]
[[!redirects history: monadic]]
[[!redirects monadic -- history]]


monadic adjunction

+-- {: .rightHandSide}
+-- {: .toc .clickDown tabindex="0"}
###Context###
#### Higher algebra
+--{: .hide}
[[!include higher algebra - contents]]
=--
#### 2-Category theory
+--{: .hide}
[[!include 2-category theory - contents]]
=--
=--
=--

# Monadic adjunctions
* table of contents
{: toc}

## Idea

One can turn [[monads]] into [[adjunctions]] and adjunctions into monads (see [there](monad#RelationBetweenAdjunctionsAndMonads)), but one doesn\'t always return where one started.  Every monad comes from an adjunction, but only a _monadic adjunction_ comes from a monad via a [[monadic functor]].  (To be fair, there are two ways to turn a monad into an adjunction, given by the [[Kleisli category]] and the [[Eilenberg–Moore category]]; we are talking about the latter here.)

## Definition

We give the definitions in [[Cat]] and leave it to future readers and writers to generalise.  See for instance ([Riehl-Verity 13](#RiehlVerity13)).

Let $(C,D,\ell,r,\iota,\epsilon)$ be an adjunction in $Cat$; that is, $\ell: C \to D$ and $r: D \to C$ are [[adjoint functors]] with $\ell \dashv r$, where $\iota$ and $\epsilon$ are the unit and counit.  Let $T$ be $r \circ \ell$; $T$ has the structure of a monad on $C$, so consider the [[Eilenberg–Moore category]] $C^T$ of [[module for a monad|modules (algebras)]] for $T$.  Then $r \circ \epsilon: T \circ r \to r$ endows $r: D \to C$ with a $T$-algebra structure, hence defines a [[functor]] $k: D \to C^T$.

The adjunction $\ell \dashv r$ is __monadic__ if this functor $k$ is an [[equivalence of categories]].

## Beck's monadicity theorem

__Beck's Monadicity Theorem__ gives a necessary and sufficient condition for an adjunction to be monadic.  Namely, the adjunction $(C,D,\ell,r,\iota,\epsilon)$ is monadic iff:

*  $r$ reflects isomorphisms; and

*  $D$ has coequalizers of $r$-split coequalizer pairs, and $r$ preserves those coequalizers.

See [[monadicity theorem]] for more details and variants.

## Algebraic categories

The typical categories studied in [[algebra]], such as [[Grp]], [[Ring]], etc, all come equipped with monadic adjunctions from [[Set]].  Specifically, the [[right adjoint]] is the [[forgetful functor]] from algebras to sets, and the [[left adjoint]] maps each set to the [[free object|free]] algebra on that set.  Their composite (a monad on $Set$) may be thought of as mapping a set $A$ to the set of words with alphabet taken from $A$ and the connections between letters taken from the appropriate algebraic operations, with two words identified if they can be proved equal by the appropriate algebraic axioms.

Abstractly, one may *define* an [[algebraic category]] to be a category equipped with a monadic adjunction from $Set$.  However, there are now more examples than the ones from algebra; the best known of these is the category of [[compact Hausdorff spaces]], which corresponds to the [[ultrafilter]] monad.  (This result relies on the [[ultrafilter principle]], regardless of whether one interprets 'space' here as referring to [[topological spaces]] or [[locales]].)

## Semantics-structure adjunction

The relationship between monads and adjunctions itself constitutes an adjunction called the **semantics-structure adjunction**. Explicitly, for a category $C$ there exist contravariant functors $Str:Cat_{/C}^*\to Mon(C):Sem$ with $Str\dashv Sem$ where $Cat_{/C}^*$ denotes the full subcategory of $Cat_{/C}$ consisting of functors admitting a codensity monad; $Str$ sends a functor to its corresponding codensity monad and $Sem$ sends a monad to the forgetful functor from its E-M category to $C$. Intuitively speaking we may think of a monad as a kind of structure with which the objects of $\mathcal{C}$ can be equipped presented in a syntax-independent way, and we may think of the E-M category of a monad (viewed as a syntax independent presentation of an equational theory) as the category of models of this theory, which is often referred to by logicians as the semantics of the theory. For more on this, see for instance section 5 of ([Schäppi 2009](#DanielSchäppi1)).

## Examples

1. [[Eilenberg-Moore categories]] are obviously all examples, and up to equivalence, the only examples.
2. If the categories are pre-orders, then a monadic adjunction is a [[Galois connection]] where the right adjoint reflects ordering and dually a comonadic adjunction is a Galois connection where the left adjoint reflects ordering.
3. More generally an [[idempotent adjunction]] is monadic if and only if the right adjoint is [[fully faithful]], i.e. essentially a [[reflective subcategory]] inclusion. Dually, a comonadic idempotent adjunction is essentially a [[coreflective subcategory]] inclusion.

## Related pages

* [[monadic functor]]
* [[monadic decomposition]]
* [[nuclear adjunction]]

## References

* [[Michael Barr]] and [[Charles Wells]], _Toposes, Triples and Theories_ ([online](http://www.tac.mta.ca/tac/reprints/articles/12/tr12abs.html))

Discussion for [[quasi-categories]] is around definition 6.1.15 and definition 7.1.6 in

* {#RiehlVerity13} [[Emily Riehl]], [[Dominic Verity]], _Homotopy coherent adjunctions and the formal theory of monads_ ([arXiv:1310.8279](http://arxiv.org/abs/1310.8279))

* {#DanielSchäppi1} Daniel Schäppi, _Tannaka duality for comonoids in cosmoi_ ([arXiv:0911.0977](https://arxiv.org/abs/0911.0977))

* Alec Rhea ([MO user page](https://mathoverflow.net/users/92164/alec-rhea)), _Semantics-structure adjunction_, URL (version: 2019-01-13): <https://mathoverflow.net/q/320698>

[[!redirects semantics-structure adjunction]]
[[!redirects structure-semantics adjunction]]

[[!redirects monadic adjunctions]]


monadic algebra

# Monadic algebras
* table of contents
{: toc}

## Idea

Monadic algebras are type one [[modal algebras]], in which  the single operator behaves like a [[topological closure|closure]] operation in a [[topological space]], (so these are [[closure algebras]]) and, in addition, elements are closed if and only if they are open.

## Definitions

+-- {: .un_defn}
###### Definition

A **monadic algebra** is a [[closure algebra]], $(\mathbb{B}, m)$, which satisfies:
for all $x$, $x\leq l m x$,
where, as usual, $l$ is a shorthand for $\neg m \neg$.
=--

[[!redirects monadic algebra]]
[[!redirects monadic algebras]]


monadic cohomology

+-- {: .rightHandSide}
+-- {: .toc .clickDown tabindex="0"}
###Context###
#### Higher algebra
+--{: .hide}
[[!include higher algebra - contents]]
=--
#### Cohomology
+--{: .hide}
[[!include cohomology - contents]]
=--
=--
=--

#Contents#
* table of contents
{:toc}

## Idea
Every [[monad]] induces an augmented cosimplicial [[endofunctor]]; in an [[additive category]] we can produce a cochain complex out of any such cosimplicial endofunctor when applied to any particular object. Taking the [[cohomology]] of that complex yields **monadic cohomology**, see [here](canonical+resolution#monadiccohomology) at *[[canonical resolution]]*.

## Related concepts

* [[cohomology]]

* [[canonical resolution]]

## References

On [[monad|monadic]] [[cohomology]] and [[comonad|comonadic]] [[homology]]:

* [[Michael Barr]], [[Jon Beck]], _Homology and Standard Constructions_, in: _[[Seminar on Triples and Categorical Homology Theory]]_, Lecture Notes in Maths. **80**, Springer (1969), Reprints in Theory and Applications of Categories __18__ (2008) 186-248 [[TAC:18](http://www.tac.mta.ca/tac/reprints/articles/18/tr18abs.html), [pdf](http://www.tac.mta.ca/tac/reprints/articles/18/tr18.pdf)]

*  {#Duskin75} [[John Duskin]], *Simplicial methods and the interpretation of "triple" cohomology"*  Memoirs  of the AMS **163**, Amer. Math. Soc. (1975) [[ISBN:978-1-4704-0645-5](https://bookstore.ams.org/memo-3-163)]

For [[algebras]], in relation to [[Hochschild cohomology]]:

* [[Michael Barr]], *Cohomology in tensored categories*, [[Proceedings of the Conference on Categorical Algebra - La Jolla 1965]], Springer (1966) 344–354 [[doi:10.1007/978-3-642-99902-4_17](https://doi.org/10.1007/978-3-642-99902-4_17), [pdf](https://www.math.mcgill.ca/barr/papers/ctc.pdf), [[Barr-CohomologyTensored.pdf:file]]]

* [[Michael Barr]], *Shukla cohomology and triples*, J. Algebra **5** 2 (1967) 222–231 [doi:10.1016/0021-8693(67)90036-1, [pdf](https://www.math.mcgill.ca/barr/papers/shukla.pdf), [[Barr-ShuklaCohomology.pdf:file]]]

* [[Michael Barr]], *Harrison homology, Hochschild homology and triples* J. Algebra **8** 3 (1968) 314–323 [doi:10.1016/0021-8693(68)90062-8, [pdf](https://www.math.mcgill.ca/barr/papers/harr-hoch.pdf), [[Barr-HarrHochAndTriples.pdf:file]]]

* [[Michael Barr]], *Cohomology and obstructions: commutative algebras*, in: _[[Seminar on Triples and Categorical Homology Theory]]_, Lecture Notes in Maths. **80**, Springer (1969), Reprints in Theory and Applications of Categories __18__ (2008) 357–374 [[TAC:18](http://www.tac.mta.ca/tac/reprints/articles/18/tr18abs.html), [pdf](http://www.tac.mta.ca/tac/reprints/articles/18/tr18.pdf), [pdf](https://www.math.mcgill.ca/barr/papers/obstruct.pdf)]

See also:

* [[Michael Barr]], *Cartan-Eilenberg cohomology and triples*, J. Pure Applied Algebra **112** 3 (1996) 219–238 \[doi:10.1016/0022-4049(95)00138-7, [pdf](https://www.math.mcgill.ca/barr/papers/coho.pdf), [[Barr-CECohomology.pdf:file]]\]

* [[Michael Barr]], *Algebraic cohomology: the early days*, in *Galois Theory, Hopf Algebras, and Semiabelian Categories*, Fields Institute Communications **43** (2004) 1–26 \[doi:10.1090/fic/043, [pdf](https://www.math.mcgill.ca/barr/papers/algcohom.pdf), [[Barr-AlgebraicCohomology.pdf:file]]\]