It depends on my previous question: Sequence of both Scalaz WriterT and personal s .
The following code block is an example of a sequence Future, Eitherand Writerusing monad transformers EitherTand WriterT; next question: how to subtly change the behavior of this package of transformers.
import scalaz._, Scalaz._
class Example[F[_], L] (val logFn: (String) => L)(implicit val f: Monad[F], l: Monoid[L])
{
type T = Throwable
type EF[α] = EitherT[F, T, α]
type WEF[α] = WriterT[EF, L, α]
private def unreliableInt (i: Int): T Either Int = new java.util.Random ().nextBoolean match {
case false => Right (i)
case true => Left (new Exception (":-("))
}
private def fn (i: Int): WEF[Int] = WriterT.put[EF, L, Int](EitherT.fromEither[F, T, Int](f.point (unreliableInt (i))))(l.zero)
private def log (msg: String): WEF[Unit] = WriterT.put[EF, L, Unit](EitherT.right[F, T, Unit](f.point (())))(logFn (msg))
private def foo (): WEF[Int] = for {
_ <- log ("Start")
x <- fn (18)
_ <- log ("Middle")
y <- fn (42)
_ <- log ("End")
} yield x + y
def bar (): F[(Option[Int], L)] = {
val barWEF: WEF[Int] = foo ()
val logsEF: EF[L] = barWEF.written
val logsF: F[L] = logsEF.toEither.map {
case Right (x) => x
case Left (e) => logFn(s"Not the logs we are looking for ${e.getMessage}")
}
val resEF: EF[Int] = barWEF.value
val resF: F[Option[Int]] = resEF.run.map {
case \/- (r) => r.some
case -\/ (ex) => None
}
for {
logs <- logsF
response <- resF
} yield (response, logs)
}
}
object Program
{
def main (args : Array[String]) = {
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global
type L = List[String]
type F[α] = Future[α]
implicit val l: Monoid[L] = new Monoid[L] { def zero = Nil; def append (f1: L, f2: => L) = f1 ::: f2 }
implicit val f: Monad[F] = scalaz.std.scalaFuture.futureInstance
def createLog (s: String) = s :: Nil
val example = new Example[F, L] (createLog)
val result = Await.result (example.bar (), 5 seconds)
println ("Context logs attached:" + result._2.foldLeft ("") { (a, x) => a + "\n$ " + s"$x"})
println ("Result:" + result._1)
}
}
The function foodoes not behave as I need; function barand function mainillustrate the problem.
The desired behavior is such that it mainalways prints one of the following results:
Context logs attached:
$ Start
Result:None
or
Context logs attached:
$ Start
$ Middle
Result:None
or
Context logs attached:
$ Start
$ Middle
$ End
Result:Some(60)
However, the function mainnever prints the following:
Context logs attached:
$ Not the logs we are looking for :-(
Result:None
, . fn1 fn2 , foo , main . fn1 fn2 Left, bar , main . , .
, , -\/, ...
Scalaz WriterT, :
final case class WriterT[F[_], W, A](run: F[(W, A)])
WriterT - case, run. run (A) , EitherT (F). W A , .
, WriterT, -, , Applicative[F].point:
final case class WriterT[F[_], W, A](wF: F[W], vF:F[A]) {
def run: F[(W, A)] = for {
w <- wF
v <- vF
} yield (w, v)
}
, WriterT .
?