Scala - monads

Monads

帶有mapflatMap方法的數據結構很常見。實際上,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,

  1. List is a monad with unit(x) = List(x)
  2. Set is monad with unit(x) = Set(x)
  3. Option is a monad with unit(x) = Some(x)
  4. Generator is a monad with unit(x) = single(x)

這些類型中都包含了同樣的flatMap方法,然而unit方法對于每個monad都要不同定義。

Monads and Map

對于每個monad,可以通過flatMapunit來定義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:

  1. Associativity:
(m flatMap f) flatMap g == m flatMap (x => f(x) flatMap g)
  1. Left unit
unit(x) flatMap f == f(x)
  1. Right unit
m flatMap unit == m

Example of Checking Monad Laws

下面舉一個例子,證明Option符合monad laws。首先給出OptionflatMap的定義。

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),由于OptionUnit定義為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

  1. 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
  1. Right unit says:
   for (x <- m) yield x == x
  1. 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對象的語法,需要定義TryObject類型,并且實現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)

如果computeXcomputeY成功運行得到結果Success(x)和結果Success(y),那么該表達式返回Success(f(x, y));如果上面兩個運算只要有一個出現錯誤,該表達式返回Failure(ex)

為了支持for表達式,需要在Try類型上定義mapflatMap方法。定義如下所示:

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容