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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With