Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reader writer state monad - how to run this scala code

Tony Morris gave a talk with this snippet.

He's using ReaderWriterState monad to provide controlled read/write access to an implicit context. That makes sense.

How do I use the code? I would like to see an example "main" program that uses this monad.

like image 699
Dustin Getz Avatar asked Jul 23 '12 19:07

Dustin Getz


1 Answers

Scalaz 7 now provides this monad, and the following is a complete working example, translated with minor revisions from the example by Michael Pilquist that's linked in the comments above.

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(), "")))
}

This is tested against Scalaz 7.2.18, which is easily available from Maven's Central Repository as a Maven or SBT dependency.

like image 181
Travis Brown Avatar answered Nov 14 '22 18:11

Travis Brown