[英]Understanding monads in scala
I'm trying to understand what monads are (not just in scala, but by example using scala). 我试图了解什么是monad(不仅在scala中,而且通过使用scala为例)。 Let's consider the most (in my opinion) simple example of a monad: 让我们考虑一个单子最简单的例子:
scala.Some
As some articles state, every monad in its classic sense should preserve some rules for the flatMap
and unit
functions. 正如某些文章所指出的那样, 经典意义上的每个monad应该为flatMap
和unit
函数保留一些规则。
Here is the definition from scala.Some
这是来自scala.Some
的定义。
@inline final def flatMap[B](f: A => Option[B]): Option[B]
So, understand it better I want to understand it from the category theory standpoint . 因此,要更好地理解它,我想从范畴论的角度来理解它。 So, we're considering a monad and it's supposed to be a functor ( but between what? ). 因此,我们正在考虑一个monad,它应该是一个函子( 但介于什么之间? )。
Here we have to category Option[A]
and Option[B]
and the flatMap
along with the f: A => Option[B]
passed into it is supposed to define a Functor between them. 在这里,我们必须对Option[A]
和Option[B]
以及flatMap
以及f: A => Option[B]
传入其中的f: A => Option[B]
应该在它们之间定义一个Functor 。 But in the tranditional category definition it's a functor from a category to itself. 但是在传统类别定义中,它是从类别到其本身的函子。
The category is the category of scala types, where the objects are types and the arrows are functions between values of those types. 类别是scala类型的类别,其中对象是类型,箭头是这些类型的值之间的函数。 Option
is an endofunctor on this category. Option
是此类的endofunctor。 For each object (ie type) in the Scala category, the Option
type constructor maps each type A
into a type Option[A]
. 对于Scala类别中的每个对象(即类型), Option
类型构造函数都将每个类型A
映射到类型Option[A]
。
In addition it maps each arrow f: A => B
into an arrow fo: Option[A] => Option[B]
which is what Option.map
does. 另外,它将每个箭头f: A => B
映射到箭头fo: Option[A] => Option[B]
,这是Option.map
作用。
A Monad is a Functor M
along with two operations, unit: A => M[A]
and join: M[M[A]] => M[A]
. Monad是函子M
,它具有两个运算符,分别是unit: A => M[A]
和join: M[M[A]] => M[A]
。 For Option
, unit(x: A) = Some(x)
and join
can be defined as: 对于Option
, unit(x: A) = Some(x)
和join
可以定义为:
def join[A](o: Option[Option[A]]): Option[A] = o match {
case None => None
case Some(i) => i
}
flatMap
can then be defined as, flatMap(f, m) = join(map(f, m))
. flatMap
然后可以被定义为, flatMap(f, m) = join(map(f, m))
Alternatively the monad can be defined using unit
and flatMap
and join
defined as join(m) = flatMap(id, m)
. 或者,可以使用unit
和flatMap
定义monad,将join
定义为join(m) = flatMap(id, m)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.