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的認識。