A comonad is the exact categorical dual of a monad: an endofunctor
A comonad on
-
$W : \mathcal{C} \to \mathcal{C}$ is an endofunctor -
$\varepsilon : W \Rightarrow \mathrm{Id}$ is the counit (natural transformation; calledextractin Haskell) -
$\delta : W \Rightarrow W \circ W$ is the comultiplication / duplicate (natural transformation)
Dually to the monad's Kleisli triple, the comonad has a co-Kleisli triple:
extract :: W a -> a— observe the focused valueextend :: (W a -> b) -> W a -> W b— shift the focus and re-observe (cokleisli extension)
The two presentations are related by:
For a comonad
- The same objects as
$\mathcal{C}$ - Morphisms
$A \to B$ in$\mathcal{C}^W$ are morphisms$W A \to B$ in$\mathcal{C}$ (co-Kleisli arrows) - Composition of
$f : W A \to B$ and$g : W B \to C$ is$g \circ_W f = g \circ W f \circ \delta_A$ - Identity:
$\varepsilon_A : W A \to A$
| Monad | Comonad |
|---|---|
return) |
extract) |
join) |
duplicate) |
| Kleisli arrow |
Co-Kleisli arrow |
>>= (bind) |
=>> (cobind / extend) |
| models effects flowing in | models context flowing out |
Counit left:
Counit right:
Co-associativity:
These are exactly the monad laws with all arrows reversed.
| CT concept | Haskell |
|---|---|
| Comonad |
class Functor w => Comonad w |
| Counit |
extract :: w a -> a |
| Comultiplication |
duplicate :: w a -> w (w a) |
| Extension |
extend :: (w a -> b) -> w a -> w b |
| Co-Kleisli arrow |
w a -> b (context-dependent transform) |
Store s a comonad |
Lens as a comonad: extract = get, extend = sets
|
Env e a comonad |
Reader as a comonad (reads from fixed environment) |
Traced m a comonad |
Writer dual: produces values indexed by a monoid |
The Store comonad Store s a = (s -> a, s) is the denotational basis of the Lens type: a lens
is precisely a co-Kleisli arrow of Store.
→ FP track: 20. Comonad | 27. Lens / Optics (Store comonad as lens) | 19. Monad (the dual)
| Resource | Link |
|---|---|
| CTFP blog — Comonads | Part 3 Ch 7 |
| CTFP LaTeX source Ch 3.7 | src/content/3.7/ |
- Monad — the categorical dual; reversing all arrows gives the comonad laws
- Adjunction — every adjunction gives both a monad and a comonad
- F-Algebra — coalgebras (the dual of algebras) are the formal basis of anamorphisms; comonads arise as terminal coalgebras