1.
Data structures with map and flatMap seem to be quite common.
In fact there’s a name that describes this class of a data structures
together with some algebraic laws that they should have.
They are called monads.
带有map和flatMap的数据结构非常常见
具有这类数据结构加上一些代数规则的类就叫做monads
2. flatMap和Unit
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]
3.Examples of 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 is an operation on each of these types, whereas unit in Scala is
different for each monad
4. 在monads上用flatMap和Unit定义map
m map f == m flatMap(x => unit(f(x)))
5. monads laws
结合律
m flatMap f flatMap g == m flatMap (x => f(x) flatMap g)
左单位
unit(x) flatMap f == f(x)
右单位
m flatMap unit = m
6.monads与for表达式
结合律使得下面两个语句等价
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
右单元使得
for (x <- m) yield x == m
7. Try类型
abstract class Try[+T] case class Success[T](x: T) extends Try[T] case class Failure(ex: Exception) extends Try[Nothing]
An expression composed from ‘Try‘, ‘map‘, ‘flatMap‘ will never
throw a non-fatal exception.
由try map flatMap构成的语句永远不会抛出非致命的异常
这个性质叫做 "bullet prooof"原理
(至今不太理解)