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的认识。

你可能感兴趣的:(Scala - monads)