Монада является моноидом, если заменить декартово произведение множеств
композицией функторов (монада является функтором), умножение — функцией join
,
а единицу — pure
. Законы моноида при этом выполняются.
Mac Lane S. Categories for the Working Mathematician. — Springer, 1998:
A monad T = \<T, η, μ> in a category X consists of a functor T: X → X and two natural transformations η: IX → T, μ: T2 → T, which make the following diagrams commute <...>*.
Formally, the definition of a monad is like that of a monoid M in sets <...>. The set M of elements of the monoid is replaced by the endofunctor T: X → X, while the cartesian product ⨯ of two sets is replaced by composite of two functors, the binary operation μ: M ⨯ M → M of multiplication by the transformation μ: T2 → T and the unit (identity) element η: 1 → M by η: IX → T. We shall thus call η the unit and μ the multiplication of the monad T; the first commutative diagram <...> is then the associative law for the monad, while the second and third diagrams express the left and right unit laws, respectively. All told, a monad in X is just a monoid in the category of endofunctors of X, with product ⨯ replaced by composition of endofunctors and unit set by the identity endofunctor.
* Диаграммы, на которые ссылается текст, описывают известные законы монад.
Свяжем это с монадами в Haskell. T — это Monad m ⇒ m a
, η — это pure ::
Monad m ⇒ a → m a
, а μ — join :: Monad m ⇒ m (m a) → m a
.
Напомню, что эта категория называется Hask. В ней объектами являются типы
Haskell, а морфизмами — функции. Композиция морфизмов — это (.)
, единичный
морфизм — id
.
Функторы Haskell Functor
являются функторами из Hask в подмножество
Hask, состоящее из типов, образованных приписыванием конструктора. То есть
типу a
ставится в соответствие тип m a
, а функции a → b
— функция m a → m
b
.