参考:
****Category
A category is, in essence, a simple collection. It has three components:
一个范畴,有3个成分:
* A collection of objects.
一些对象,一些一般的东西(meta?).
* A collection of morphisms, each of which ties two objects (a source object and a target object) together.
(These are sometimes called arrows, but we avoid that term here as it has other connotations in Haskell.)
If f is a morphism with source object A and target object B, we write "f: A -> B".
一些"射",每个射都绑定了两个东西 A -> B.
* A notion of composition of these morphisms. If h is the composition of morphisms f and g, we write "h = f . g"
射的组合, h = f.g
****Functor
The next Big Topic in category theory is the functor, which relates categories together.
A functor is essentially a transformation between categories, so given categories C and D, a functor F : C -> D
Functor表示了两个"范畴"之间的转化.
* Maps any object A in C to F(A), in D.
映射C中的"东西"到D中, A表示C中的东西,则F(A)表示D中的东西.
* Maps morphisms "f: A -> B" in C to F(f) : F(A) -> F(B) in D.
映射C中的"射"到D中, 对于C中的"f : A -> B",到D中的"F(f) : F(A) -> F(B)", 也就是f映射为F(f).
id是"自射", 映射到相同的范畴.
一些axiom(公理):
* F(id (A)) 等价于 id (F (A))
* F(f.g) 等价于 F(f).F(g) -- Functor可以游走于(.)内外.
Haskell中的Functor:
fmap :: (a -> b) -> (f a -> f b)
范畴学中概念与Haskell的对应:
* Objects 对应 types "东西"就是数据
* Morphisms 对应 functions "射"就是函数
* Things that take a type and return another type are type constructors.
拿走一种类型而返回另一种类型的玩意是类型构造器.
* Things that take a function and return another function are higher-order functions.
拿走一种函数而返回另一种函数的玩意是高阶函数.
* Typeclasses, along with the polymorphism they provide, make a nice way of capturing
the fact that in category theory things are often defined over a number of objects at once.
"类",与其提供的"多态",构成了"一次定义,多处可用"的好形式.
****Monads
Monads are obviously an extremely important concept in Haskell,
and in fact they originally came from category theory.
A monad is a special type of functor, from a category to that same category,
that supports some additional structure. So, down to definitions.
A monad is a functor "M : C -> C", along with two morphisms[2] for every object X in C:
* unit : X -> M(X)
* join : M(M(X)) -> M(X)
{return, fmap, join} 和 {return, >>=} 是等价的
几个有意思的等价性:
* join . fmap join = join . join
对于两级"联合",首先进行哪级都是不影响最终结果的.左边的两个join相当于右边的顺序逆反过来.
* join . fmap return = join . return = id
先降级再升级 == 先提升再降级 == 什么都没做.
* return . f = fmap f . return
操作后提升 == 提升后解剖操作再缝合.
* join . fmap (fmap f) = fmap f . join
剖开2层操作在提升 == 提升后剖开一层操作.
这些都是有趣的"我又进来了,我又出去了,打我啊打我啊!"这句台词的翻版,在哪打都一样!
后面是do和monad的分析,就用到了这上面的一些原理.
进行了各种啰嗦的等价性证明,大致就是提来降去的...