Tra*_*own 19
Scalaz 7现在提供了这个monad,以下是一个完整的工作示例,由Michael Pilquist的示例进行了少量修订,并在上面的注释中进行了链接.
package scalaz.example
import scalaz._, Scalaz._
object RWSExample extends App {
case class Config(port: Int)
def log[R, S](msg: String): ReaderWriterState[R, List[String], S, Unit] =
ReaderWriterStateT {
case (r, s) => (msg.format(r, s) :: Nil, (), s).point[Id]
}
def invokeService: ReaderWriterState[Config, List[String], Int, Int] =
ReaderWriterStateT {
case (cfg, invocationCount) => (
List("Invoking service with port " + cfg.port),
scala.util.Random.nextInt(100),
invocationCount + 1).point[Id]
}
val program: RWS[Config, List[String], Int, Int] = for {
_ <- log("Start - r: %s, s: %s")
res <- invokeService
_ <- log("Between - r: %s, s: %s")
_ <- invokeService
_ <- log("Done - r: %s, s: %s")
} yield res
val (logMessages, result, invocationCount) = program run (Config(443), 0)
println("Result: " + result)
println("Service invocations: " + invocationCount)
println("Log: %n%s".format(logMessages.mkString("\t", "%n\t".format(), "")))
}
Run Code Online (Sandbox Code Playgroud)
这是针对Scalaz 7.2.18进行测试的,它可以从Maven的Central Repository 轻松获得,作为Maven或SBT依赖.
| 归档时间: |
|
| 查看次数: |
2372 次 |
| 最近记录: |