代码之家  ›  专栏  ›  技术社区  ›  Dustin Getz sunsations

读写器状态monad-如何运行此scala代码

  •  18
  • Dustin Getz sunsations  · 技术社区  · 12 年前

    托尼·莫里斯用这个做了演讲 snippet

    他使用ReaderWriterState monad来提供对隐式上下文的受控读/写访问。这是有道理的。

    我该如何使用代码?我希望看到一个使用这个monad的“main”程序示例。

    1 回复  |  直到 12 年前
        1
  •  19
  •   Mohan Narayanaswamy    7 年前

    Scalaz 7 现在提供了这个monad,下面是一个完整的工作示例,从 the example by 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(), "")))
    }
    

    这是针对Scalaz 7.2.18进行的测试 easily available 作为Maven或SBT依赖项从Maven的中央存储库中删除。