A monad is just a monoid in the category of endofunctors, what's the problem?
作为一个计算机工作者,这句话对你造成过多少点的装逼伤害?是时候弄明白这句话的意思了。
搞清楚Monad需要了解的概念
1. Category:

注意:
1. Category与集合不同,不只包括元素(objects),还包括了元素之上的态射(morphisms),态射的二元运算∘还需满足结合律(associativity),并且对identity的存在性有要求。
2. 给定Category C,C的元素ob(C)是一个类(class),类是比集合(set)大的一个概念,两者区别可以从罗素悖论(Russell paradox)进一步了解。如果不想分散注意力,暂时可以认为该类就是一个集合。
3. 二元运算是态射的运算,不是元素的
2. Functor

Functor是个范畴与范畴之间的映射(mapping)。可以看作是范畴间的同态(homomorphism),其特点是保留结构(structure-preserving)的,所谓结构保留体现在不只映射元素,同时映射态射。如下图所示:

根据范畴的定义,很自然的可以得出:

3. Endofunctor
A functor that maps a category to itself.
endofunctor的概念很简单,但是,是不是endofunctor就是identity functor呢?并不是,如果那样想,就是给endofunctor额外的限制了。试着看下图

再来一图

4. Natural transformations

一句话解释,自然变换(Natural Transformation)就是对于属于Category C的任意X,F(X)到G(X)之间态射的集合。注意F(X)与G(X)都属于Category D。类比于codomain,自然变换在"co-category"上。
5. Monad

Monad简单说就是1+2,1个endofunctor+2个natural transformations。
η的含义比较简单,根据定义,1c是identity functor,显然是一个特殊的endofunctor。根据自然变换的定义1c->T不能理解。
μ的含义需要先理解T∘T的意思,即对范畴进行两次mapping,不难得出T∘T依然是endofunctor。
看个图:

看看什么是a monoid in the category of endofunctors
1. Monoid

2. The category of endofunctors
这个Category我们记作[C,C],简单说,就是所有C->C的endofunctors构成的范畴,这个范畴的元素是endofunctors,态射是自然变换。注意,[C,C]是一个monoidal category,这个在网上可以找到证明,此处不赘述。
So, A monad is a monoid in the category of endofunctors
到此时,很容易发现,什么是monad的两种描述,本质上描述的是相同的东西。就是一个1+2(1个endofunctors,加2个特殊的自然变换)
注意
wiki上还有定义说monoid是一个满足特殊条件的 Set,那到底monoid是Set还是Endofunctor呢?我在另外一篇文章做了解释。
网友评论