通过前面的几篇讨论我们了解到F[T]就是FP中运算的表达形式(representation of computation)。在这里F[]不仅仅是一种高阶类型,它还代表了一种运算协议(computation protocol)或者称为运算模型好点,如IO[T],Option[T]。运算模型规范了运算值T的运算方式。而Monad是一种特殊的FP运算模型M[A],它是一种持续运算模式。通过flatMap作为链条把前后两个运算连接起来。多个flatMap同时作用可以形成一个程序运行链。我们可以在flatMap函数实现中增加一些附加作用,如维护状态值(state value)、跟踪记录(log)等。

在上一篇讨论中我们用一个Logger的实现例子示范了如何在flatMap函数实现过程中增加附加作用;一个跟踪功能(logging),我们在F[T]运算结构中增加了一个String类型值作为跟踪记录(log)。在本篇讨论中我们首先会对上篇的Logger例子进行一些log类型的概括,设计一个新的Logger结构:

 case class Logger[LOG, A](log: LOG, value: A) {
def map[B](f: A => B): Logger[LOG,B] = Logger(log, f(value))
def flatMap[B](f: A => Logger[LOG,B])(implicit M: Monoid[LOG]): Logger[LOG,B] = {
val nxLogger = f(value)
Logger(log |+| nxLogger.log, nxLogger.value)
} }

以上Logger对LOG类型进行了概括:任何拥有Monoid实例的类型都可以,能够支持Monoid |+|操作符号。这点从flatMap函数的实现可以证实。

当然我们必须获取Logger的Monad实例才能使用for-comprehension。不过由于Logger有两个类型参数Logger[LOG,A],我们必须用type lambda把LOG类型固定下来,让Monad运算只针对A类型值:

 object Logger {
implicit def toLogger[LOG](implicit M: Monoid[LOG]) = new Monad[({type L[x] = Logger[LOG,x]})#L] {
def point[A](a: => A) = Logger(M.zero,a)
def bind[A,B](la: Logger[LOG,A])(f: A => Logger[LOG,B]): Logger[LOG,B] = la flatMap f
}
}

有了Monad实例我们可以使用for-comprehension:

 def enterInt(x: Int): Logger[String, Int] = Logger("Entered Int:"+x, x)
//> enterInt: (x: Int)Exercises.logger.Logger[String,Int]
def enterStr(x: String): Logger[String, String] = Logger("Entered String:"+x, x)
//> enterStr: (x: String)Exercises.logger.Logger[String,String] for {
a <- enterInt()
b <- enterInt()
c <- enterStr("Result:")
} yield c + (a * b).shows //> res0: Exercises.logger.Logger[String,String] = Logger(Entered Int:3Entered I
//| nt:4Entered String:Result:,Result:12)

不过必须对每个类型定义操作函数,用起来挺不方便的。我们可以为任何类型注入操作方法:

 final class LoggerOps[A](a: A) {
def applyLog[LOG](log: LOG): Logger[LOG,A] = Logger(log,a)
}
implicit def toLoggerOps[A](a: A) = new LoggerOps[A](a)
//> toLoggerOps: [A](a: A)Exercises.logger.LoggerOps[A]

我们为任意类型A注入了applyLog方法:

 .applyLog("Int three")                           //> res1: Exercises.logger.Logger[String,Int] = Logger(Int three,3)
"hi" applyLog "say hi" //> res2: Exercises.logger.Logger[String,String] = Logger(say hi,hi)
for {
a <- applyLog "Entered Int 3"
b <- applyLog "Entered Int 4"
c <- "Result:" applyLog "Entered String 'Result'"
} yield c + (a * b).shows //> res3: Exercises.logger.Logger[String,String] = Logger(Entered Int 3Entered
//| Int 4Entered String 'Result',Result:12)

用aplyLog这样操作方便多了。由于LOG可以是任何拥有Monoid实例的类型。除了String类型之外,我们还可以用Vector或List这样的高阶类型:

 for {
a <- applyLog Vector("Entered Int 3")
b <- applyLog Vector("Entered Int 4")
c <- "Result:" applyLog Vector("Entered String 'Result'")
} yield c + (a * b).shows //> res4: Exercises.logger.Logger[scala.collection.immutable.Vector[String],Str
//| ing] = Logger(Vector(Entered Int 3, Entered Int 4, Entered String 'Result')
//| ,Result:12)

一般来讲,用Vector效率更高,在下面我们会证实这点。

既然A可以是任何类型,那么高阶类型如Option[T]又怎样呢:

 for {
oa <- .some applyLog Vector("Entered Some(3)")
ob <- .some applyLog Vector("Entered Some(4)")
} yield ^(oa,ob){_ * _} //> res0: Exercises.logger.Logger[scala.collection.immutable.Vector[String],Opti
//| on[Int]] = Logger(Vector(Entered Some(3), Entered Some(4)),Some(12))

一样可以使用。注意oa,ob是Option类型所以必须使用^(oa,ob){...}来结合它们。

我们再来看看Logger的典型应用:一个gcd(greatest common denominator)算法例子:

 def gcd(x: Int, y: Int): Logger[Vector[String], Int] = {
if (y == ) for {
_ <- x applyLog Vector("Finished at " + x)
} yield x
else
x applyLog Vector(x.shows + " mod " + y.shows + " = " + (x % y).shows) >>= {_ => gcd(y, x % y) } } //> gcd: (x: Int, y: Int)Exercises.logger.Logger[Vector[String],Int]
gcd(,) //> res5: Exercises.logger.Logger[Vector[String],Int] = Logger(Vector(18 mod 6
//| = 0, Finished at 6),6)
gcd(,) //> res6: Exercises.logger.Logger[Vector[String],Int] = Logger(Vector(8 mod 3 =
//| 2, 3 mod 2 = 1, 2 mod 1 = 0, Finished at 1),1)

注意 >>= 符号的使用,显现了Logger的Monad实例特性。

实际上scalar提供了Writer数据结构,它是WriterT类型的一个特例:

 type Writer[+W, +A] = WriterT[Id, W, A]

我们再看看WriterT:scalaz/WriterT.scala

final case class WriterT[F[_], W, A](run: F[(W, A)]) { self =>
...

WriterT在运算值A之外增加了状态值W,形成一个对值(paired value)。这是一种典型的FP状态维护模式。不过WriterT的这个(W,A)是在运算模型F[]内的。这样可以实现更高层次的概括,为这种状态维护的运算增加多一层运算协议(F[])影响。我们看到Writer运算是WriterT运算模式的一个特例,它直接计算运算值,不需要F[]影响,所以Writer的F[]采用了Id,因为Id[A] = A。我们看看WriterT是如何通过flatMap来实现状态维护的:scalaz/WriterT.scala:

  def flatMap[B](f: A => WriterT[F, W, B])(implicit F: Bind[F], s: Semigroup[W]): WriterT[F, W, B] =
flatMapF(f.andThen(_.run)) def flatMapF[B](f: A => F[(W, B)])(implicit F: Bind[F], s: Semigroup[W]): WriterT[F, W, B] =
writerT(F.bind(run){wa =>
val z = f(wa._2)
F.map(z)(wb => (s.append(wa._1, wb._1), wb._2))
})

在flatMapF函数里对(W,A)的W进行了Monoid append操作。

实际上Writer可以说是一种附加的数据结构,它在运算模型F[A]内增加了一个状态值W形成了F(W,A)这种形式。当我们为任何类型A提供注入方法来构建这个Writer结构后,任意类型的运算都可以使用Writer来实现在运算过程中增加附加作用如维护状态、logging等等。我们看看scalaz/Syntax/WriterOps.scala:

package scalaz
package syntax final class WriterOps[A](self: A) {
def set[W](w: W): Writer[W, A] = WriterT.writer(w -> self) def tell: Writer[A, Unit] = WriterT.tell(self)
} trait ToWriterOps {
implicit def ToWriterOps[A](a: A) = new WriterOps(a)
}

存粹是方法注入。现在任何类型A都可以使用set和tell来构建Writer类型了:

  set Vector("Entered Int 3")                     //> res2: scalaz.Writer[scala.collection.immutable.Vector[String],Int] = WriterT
//| ((Vector(Entered Int 3),3))
"hi" set Vector("say hi") //> res3: scalaz.Writer[scala.collection.immutable.Vector[String],String] = Writ
//| erT((Vector(say hi),hi))
List(,,) set Vector("list 123") //> res4: scalaz.Writer[scala.collection.immutable.Vector[String],List[Int]] = W
//| riterT((Vector(list 123),List(1, 2, 3)))
.some set List("some 3") //> res5: scalaz.Writer[List[String],Option[Int]] = WriterT((List(some 3),Some(3
//| )))
Vector("just say hi").tell //> res6: scalaz.Writer[scala.collection.immutable.Vector[String],Unit] = Writer
//| T((Vector(just say hi),()))

用Writer运算上面Logger的例子:

 for {
a <- set "Entered Int 3 "
b <- set "Entered Int 4 "
c <- "Result:" set "Entered String 'Result'"
} yield c + (a * b).shows //> res7: scalaz.WriterT[scalaz.Id.Id,String,String] = WriterT((Entered Int 3 En
//| tered Int 4 Entered String 'Result',Result:12))

如果A是高阶类型如List[T]的话,还能使用吗:

 for {
la <- List(,,) set Vector("Entered List(1,2,3)")
lb <- List(,) set Vector("Entered List(4,5)")
lc <- List() set Vector("Entered List(6)")
} yield (la |@| lb |@| lc) {_ + _ + _} //> res1: scalaz.WriterT[scalaz.Id.Id,scala.collection.immutable.Vector[String]
//| ,List[Int]] = WriterT((Vector(Entered List(1,2,3), Entered List(4,5), Enter
//| ed List(6)),List(11, 12, 12, 13, 13, 14)))

的确没有问题。

那个gcd例子还是挺有代表性的,我们用Writer来运算和跟踪gcd运算:

 def gcd(a: Int, b: Int): Writer[Vector[String],Int] =
if (b == ) for {
_ <- Vector("Finished at "+a.shows).tell
} yield a
else
Vector(a.shows+" mod "+b.shows+" = "+(a % b).shows).tell >>= {_ => gcd(b,a % b)}
//> gcd: (a: Int, b: Int)scalaz.Writer[Vector[String],Int] gcd(,) //> res8: scalaz.Writer[Vector[String],Int] = WriterT((Vector(8 mod 3 = 2, 3 mo
//| d 2 = 1, 2 mod 1 = 0, Finished at 1),1))
gcd(,) //> res9: scalaz.Writer[Vector[String],Int] = WriterT((Vector(16 mod 4 = 0, Fin
//| ished at 4),4))

在维护跟踪记录(logging)时使用Vector会比List更高效。我们来证明一下:

 def listLogCount(c: Int): Writer[List[String],Unit] = {
@annotation.tailrec
def countDown(c: Int, w: Writer[List[String],Unit]): Writer[List[String],Unit] = c match {
case => w >>= {_ => List("").tell }
case x => countDown(x-, w >>= {_ => List(x.shows).tell })
}
val t0 = System.currentTimeMillis
val r = countDown(c,List[String]().tell)
val t1 = System.currentTimeMillis
r >>= {_ => List((t1 -t0).shows+"msec").tell }
} //> listLogCount: (c: Int)scalaz.Writer[List[String],Unit]
def vectorLogCount(c: Int): Writer[Vector[String],Unit] = {
@annotation.tailrec
def countDown(c: Int, w: Writer[Vector[String],Unit]): Writer[Vector[String],Unit] = c match {
case => w >>= {_ => Vector("").tell }
case x => countDown(x-, w >>= {_ => Vector(x.shows).tell })
}
val t0 = System.currentTimeMillis
val r = countDown(c,Vector[String]().tell)
val t1 = System.currentTimeMillis
r >>= {_ => Vector((t1 -t0).shows+"msec").tell }
} //> vectorLogCount: (c: Int)scalaz.Writer[Vector[String],Unit] (listLogCount().run)._1.last //> res10: String = 361msec
(vectorLogCount().run)._1.last //> res11: String = 49msec

看,listLogCount(10000)用了361msec

vectorLogCount(10000)只用了49msec,快了8,9倍呢。

Scalaz(13)- Monad:Writer - some kind of logger的更多相关文章

  1. Scalaz(25)- Monad: Monad Transformer-叠加Monad效果

    中间插播了几篇scalaz数据类型,现在又要回到Monad专题.因为FP的特征就是Monad式编程(Monadic programming),所以必须充分理解认识Monad.熟练掌握Monad运用.曾 ...

  2. Scalaz(14)- Monad:函数组合-Kleisli to Reader

    Monad Reader就是一种函数的组合.在scalaz里函数(function)本身就是Monad,自然也就是Functor和applicative.我们可以用Monadic方法进行函数组合: i ...

  3. Scalaz(18)- Monad: ReaderWriterState-可以是一种简单的编程语言

    说道FP,我们马上会联想到Monad.我们说过Monad的代表函数flatMap可以把两个运算F[A],F[B]连续起来,这样就可以从程序的意义上形成一种串型的流程(workflow).更直白的讲法是 ...

  4. Scalaz(17)- Monad:泛函状态类型-State Monad

    我们经常提到函数式编程就是F[T].这个F可以被视为一种运算模式.我们是在F运算模式的壳子内对T进行计算.理论上来讲,函数式程序的运行状态也应该是在这个运算模式壳子内的,也是在F[]内更新的.那么我们 ...

  5. Scalaz(19)- Monad: \/ - Monad 版本的 Either

    scala标准库提供了一个Either类型,它可以说是Option的升级版.与Option相同,Either也有两种状态:Left和Right,分别对应Option的None和Some,不同的是Lef ...

  6. Scalaz(16)- Monad:依赖注入-Dependency Injection By Reader Monad

    在上一篇讨论里我们简单的介绍了一下Cake Pattern和Reader Monad是如何实现依赖注入的.主要还是从方法上示范了如何用Cake Pattern和Reader在编程过程中解析依赖和注入依 ...

  7. Scalaz(15)- Monad:依赖注入-Reader besides Cake

    我们可以用Monad Reader来实现依赖注入(dependency injection DI or IOC)功能.Scala界中比较常用的不附加任何Framework的依赖注入方式可以说是Cake ...

  8. Scalaz(12)- Monad:再述述flatMap,顺便了解MonadPlus

    在前面的几篇讨论里我们初步对FP有了些少了解:FP嘛,不就是F[A]吗?也是,FP就是在F[]壳子(context)内对程序的状态进行更改,也就是在F壳子(context)内施用一些函数.再直白一点就 ...

  9. Scalaz(11)- Monad:你存在的意义

    前面提到了scalaz是个函数式编程(FP)工具库.它提供了许多新的数据类型.拓展的标准类型及完整的一套typeclass来支持scala语言的函数式编程模式.我们知道:对于任何类型,我们只需要实现这 ...

随机推荐

  1. php中的常用函数

    1.随机数和时间 echo rand(); //随机数生成器 echo rand(0,10); //某个范围之间的随机数:第一个参数最小,第二个参数最大:例子是从0-10之间的随机数 echo tim ...

  2. Masonry -- 使用纯代码进行iOS应用的autolayout自适应布局

    简介 简化iOS应用使用纯代码机型自适应布局的工作,使用一种简洁高效的语法替代NSLayoutConstraints. 项目主页: Masonry 最新示例: 点击下载 项目简议: 如果再看到关于纯代 ...

  3. Leetcode 69 Sqrt(x) 二分查找(二分答案)

    可怕的同时考数值溢出和二分的酱油题之一,常在各种小公司的笔试中充当大题来给你好看... 题意很简单,在<二分查找综述>中有描述. 重点:使用简单粗暴的long long来避免溢出,二分均方 ...

  4. php的几种运行模式CLI、CGI、FastCGI、mod_php

    1.CLI:就是命令行,例如可以在控制台或者是shell中键入命令: php -f index.php 然后获取输出 2.CGI:以下是不同的说法与理解 公共网关接口”(Common Gateway  ...

  5. js连续指定两次或者多次的click事件(解决办法)

    setTimeout (表达式,延时时间)setTimeout(表达式,交互时间)延时时间/交互时间是以豪秒为单位的(1000ms=1s) setTimeout  在执行时,是在载入后延迟指定时间后, ...

  6. Js杂谈-正则的测试与回溯次数

    例子来源于<精通正则表达式(第三版)>这本书,我贴出来: 这里的NFA是正则的一种引擎,书中介绍了一共三种引擎:NFA,DFA和POSIX NFA.像一般我们常用的.NET,java.ut ...

  7. Java多线程系列--“基础篇”09之 interrupt()和线程终止方式

    概要 本章,会对线程的interrupt()中断和终止方式进行介绍.涉及到的内容包括:1. interrupt()说明2. 终止线程的方式2.1 终止处于“阻塞状态”的线程2.2 终止处于“运行状态” ...

  8. Yii2的深入学习--继承关系

    想要了解 Yii2 的话,一定要对 Yii2 中相关类的继承关系有所了解.由于暂时读的代码有限,下面的图中只列出了部分继承关系,之后回跟着源码阅读的越来越多而增加 由上图可以看到 Yii2 中大多数类 ...

  9. Android requires compiler compliance level 5.0 or 6.0. Found '1.8' instead. Please use Android Tools>Fix project Properties.

    重装操作系统之后,或者破坏了Android的开发环境之后,需要重新配置好Android的开发环境.但是配置好后,导入原有的项目时,报错: Android requires compiler compl ...

  10. CSS魔法堂:你真的理解z-index吗?

    一.前言 假如只是开发简单的弹窗效果,懂得通过z-index来调整元素间的层叠关系就够了.但要将多个弹窗间层叠关系给处理好,那么充分理解z-index背后的原理及兼容性问题就是必要的知识储备了.本文作 ...