Monads之flatMap,unit

来源:互联网 发布:大数据算法分析 编辑:程序博客网 时间:2024/05/22 02:24

Monads是个仿函数,但仿函数不一定是Monads,接下来是Monads的flatMap,unit特性

一个Monads最小化trait

trait Monad[M[_]] extends Functor[M] {def unit[A](a: => A): M[A]def flatMap[A,B](ma: M[A])(f: A => M[B]): M[B]def map[A,B](ma: M[A])(f: A => B): M[B] = flatMap(ma)(a => unit(f(a)))def map2[A,B,C](ma: M[A], mb: M[B])(f: (A, B) => C): M[C] = flatMap(ma)(a => map(mb)(b => f(a, b)))}

有两个重要的特性,unit和flatMap,以及基于flatMap实现的map和map2

unit是Monads的最小化单元,看签名就知道是怎么一回事了,不用不多解释,依据签名我们看出Monads的最小单元其实是一个类型构造器构造的类型,而flatMap与Monoids不同是入参函数的返回类型不同

一个list类型的最小化Monads

val listMonad = new Monad[List] {  def unit[A](a: => A) = List(a)  def flatMap[A,B](ma: List[A])(f: A => List[B]) = ma flatMap f}


The name "monad"

       We could have called anything at all, like Monad FlatMappable orwhatever. But "monad" is already a perfectly good name in commonuse. The name comes from category theory, a branch of mathematicsthat has inspired a lot of functional programming concepts. The name"monad" is intentionally similar to "monoid", and the two concepts arerelated in a deep way. See the chapter notes for more information.



0 0
原创粉丝点击