2

As an (applied) mathematician by training, I've been trying to get my head around monads and category theory applied to functional programming. I understand the power of monads, and notably commutative monads, to allow computations to be parallelized with guarantees that the result will be as expected irrespective of the computation orders.

It seems to me that in functional programming, monads are not, strictly speaking monads, since they are not endofunctors. Monads are defined as a monoid in the category of endofunctors. However, the canonical example is the Maybe or Option monad, e.g., here, which is a functor from category T to category Maybe<T>. I'm bothered by this, have I missed something?

It seems to be that the category of elements of type Monad<T> is in fact simply a monoid (under composition join: Monad<Monad<T>> -> Monad<T> and trivial identity), with function bind: A -> (A -> Monad<B>) -> Monad<B>) used to apply transformations of to the inner values wrapped by the monad.

One could see the monad could be the join operator itself, on the category of elements of type T, Monad<T>, Mondad<Monad<T>>, and so on and so forth, extended as follows:

  • join: T -> Monad<T> (== return)
  • join: Monad<Monad<T>> -> Monad<T>

but this is not how it is defined in, e.g., Haskell, where the join function can't be applied to objects of the original type.

Said otherwise, it seems more accurate to me to describe "monads" in the functional programming sense, as the combination of (forgive the liberties in notations):

  • A functor from category T to category Monad<T> (return)
  • An associative composition of elements of types Monad<T> to form a monoid (join)
  • A functor mapping morphisms from A to B to morphisms from Monad<A> to Mondad<B>

Am I correct in understanding that monads in functional programming do not have much in common with monads in category theory (save from the closeness with monoids and functors)?

lableue
  • 29
  • 1
  • 4
    Haskell types `T` and `Maybe T` are not a categories (at least, not categories of interest here). `T` and `Maybe T` are objects in the category [**Hask**](https://wiki.haskell.org/Hask) (the category of Haskell types). Thus `Maybe` is an endofunctor on **Hask**. – rob mayoff Jul 04 '22 at 23:43
  • 1
    Does this answer your question? [A monad is just a monoid in the category of endofunctors, what's the problem?](https://stackoverflow.com/questions/3870088/a-monad-is-just-a-monoid-in-the-category-of-endofunctors-whats-the-problem) – Bergi Jul 05 '22 at 00:03
  • In [this answer](https://stackoverflow.com/a/71813451/1598537) towards the end I introduce the Kleisli category, which is the one in which a monoid gives you a monad. Also, Monad can be considered a subcategory of T, so Monad is indeed an endofunctor. – AndrewC Jul 19 '22 at 11:08

0 Answers0