Monads
带有map
和flatMap
方法的数据结构很常见。实际上,there’s a name that describes this class of a data structures together with some algebraic laws that they should have. 他们称作Monads。
那么,什么是Monad?What is Monad?
A monad M is a parametric type M[T] with two operations, flatMap and unit, that have to satisfy some laws.
trait M[T] {
def flatMap[U](f: T => M[U]): M[U]
}
def unit[T](x: T): M[T]
通常Monad中的flatMap
称作bind
。
Examples of Monads
下面列举了Scala中的一些Monads,
- List is a monad with
unit(x) = List(x)
- Set is monad with
unit(x) = Set(x)
- Option is a monad with
unit(x) = Some(x)
- Generator is a monad with
unit(x) = single(x)
这些类型中都包含了同样的flatMap
方法,然而unit
方法对于每个monad都要不同定义。
Monads and Map
对于每个monad,可以通过flatMap
和unit
来定义map
,即:
m map f == m flatMap (x => unit(f(x))) == m flatMap (f andThen unit)
andThen
方法在表示函数的组合,f andThen unit
表示首先执行函数f
接着执行函数unit
。
Monad Laws
To qualify as a monad, a type has to satisfy three laws:
- Associativity:
(m flatMap f) flatMap g == m flatMap (x => f(x) flatMap g)
- Left unit
unit(x) flatMap f == f(x)
- Right unit
m flatMap unit == m
Example of Checking Monad Laws
下面举一个例子,证明Option
符合monad laws
。首先给出Option
对flatMap
的定义。
abstract class Option[+T] {
def flatMap[U](f: T => Option[U]): Option[U] = this match {
case Some(x) => f(x)
case None => None
}
}
- Checking the Left Unit Law
首先来证明Left Unit Law,也就是证明unit(x) flatMap f == f(x)
,由于Option
的Unit
定义为unit(x) = Some(x)
,故证明Some(x) flatMap f == f(x)
。
Some(x) flatMap f ==
Some(x) match {
case Some(x) => f(x)
case None => None
} == f(x)
- Checking the Right Unit Law
证明Right Unit Law,也就是证明m flatMap unit == m
,即证明m flatMap Some == m
。
m flatMap Some ==
m match {
case Some(x) => Some(x)
None => None
} == m
- Checking the Associative Law
最后,证明Associative Law,也就是证明(m flatMap f) flatMap g == m flatMap (x => f(x) flatMap g)
。
(m flatMap f) flatMap g ==
m match { case Some(x) => f(x) case None => None }
match { case Some(y) => g(y) case None => None } ==
m match {
case Some(x) => f(x) match { case Some(y) => g(y) case None => None }
case None => None match { case Some(y) => g(y) case None => None }
} ==
m match {
case Some(x) => f(x) match { case Some(y) => g(y) case None => None }
case None => None
} ==
m match {
case Some(x) => f(x) flatMap g
case None => None
} == m flatMap (x => f(x) flatMap g)
Significance of the Laws for For-Expressions
- Associativity says essentially that one can “inline” nested for expressions:
for (y <- for (x <- m; y <- f(x)) yield y; z <- g(y)) yield z ==
for (x <- m; y <- f(x); z <- g(y)) yield z
- Right unit says:
for (x <- m) yield x == x
- Left unit does not have an analogue for for-expressions.
Another type: Try
在后面的课程里将会用到的一个类型就是Try
,他的定义如下:
abstract class Try[+T]
case class Success[T](x: T) extends Try[T]
case class Failure(ex: Exception) extends Try[Nothing]
在Scala中Nothing
是所有类型的子类型,一般用来表示什么都没有返回,如发生了异常。
对于Try
的作用有如下解释:
Try is used to pass results of computations that can fail with an exception between threads and computers.
也就是说异常的传播可以不是通过调用栈,而是在不同的thread,不同的机器上进行传播。
你可以在Try
中封装任何计算,也就是说:
Try(expr) // gives Success(someValue) or Failure(someException)
为了支持上面的创建Try
对象的语法,需要定义Try
的Object
类型,并且实现apply
方法。apply
方法类似于()
的方法名。如下所示:
object Try {
def apply[T](expr: => T): Try[T] =
try Success(expr)
catch {
case NonFatal(ex) => Failure(ex)
}
}
}
其中的参数传递语法expr: => T
表示call by name
,也就是说传递参数时并不先进行evaluate
求值,直到进入try Success(expr)
才进行evaluate
,这也是可以在apply
内部捕捉到异常的原因。
就像Option
类型一样,Try
也可以使用for
表达式。比如:
for {
x <- computeX
y <- computeY
} yield f(x, y)
如果computeX
和computeY
成功运行得到结果Success(x)
和结果Success(y)
,那么该表达式返回Success(f(x, y))
;如果上面两个运算只要有一个出现错误,该表达式返回Failure(ex)
。
为了支持for
表达式,需要在Try
类型上定义map
和flatMap
方法。定义如下所示:
abstract class Try[T] {
def flatMap[U](f: T => Try[U]): Try[U] = this match {
case Success(x) => try f(x) catch { case NonFatal(ex) => Failure(ex) }
case fail: Failure => fail
}
def map[U](f: T => U): Try[U] = this match {
case Success(x) => Try(f(x))
case fail: Failure => fail
}
}
其实,map
是可以由flatMap
定义的:
t map f == t flatMap (x => Try(f(x))) == t flatMap (f andThen Try)
问题来了,定义了unit = Try
后,Try
是不是一个monad呢?答案是:不符合left unit law
,也就是Try(expr) flatMap f != f(expr)
。为什么呢?课上给的解释是:
Indeed the left-hand side will never raise a non-fatal exception whereas the right-hand side will raise any exception thrown by expr or f.
由Left unit does not have an analogue for for-expressions这条结论可以验证,即使Try
违法了left unit law
他也可以使用for
表达式。
Monad这一概念很抽象,也不怎么好理解,需要在以后的课程中使用Monad的特性来加深对Monad的认识。
网友评论