Setting up the composition of Future, Either, and Writer in Scalaz

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 ()

    // Pull out the logs.
    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}")
    }

    // Pull out the value.
    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 .

?

+2
1

: , .

...

type MyMonad e w a = ErrorT e (Writer w) a (Either e a, w)

type MyMonad e w a = WriterT w (Either e) a Either r (a, w)

:

import scalaz._, Scalaz._

class Example[F[_], L] (val logFn: (String) => L)(implicit val f: Monad[F], l: Monoid[L])
{
  type T = Throwable
  type WF[α] = WriterT[F, L, α]
  type EWF[α] = EitherT[WF, T, α]

  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): EWF[Int] = unreliableInt (i) match {
    case Left (left) => EitherT.left [WF, T, Int] (WriterT.put[F, L, T] (f.point (left))(l.zero))
    case Right (right) => EitherT.right [WF, T, Int] (WriterT.put[F, L, Int] (f.point (right))(l.zero))
  }

  private def log (msg: String): EWF[Unit] = { EitherT.right[WF, T, Unit](WriterT.put[F, L, Unit] (f.point (()))(logFn (msg))) }

  private def foo (): EWF[Int] = for {
    a <- log ("Start")
    x <- fn (18)
    b <- log ("Middle")
    y <- fn (42)
    c <- log ("End")
  } yield x + y

  def bar (): F[(Option[Int], L)] = {
    val barEWF: EWF[Int] = foo ()

    // Pull out the logs.
    val logsF: F[L] = barEWF.run.written

    // Pull out the value.
    val resF: F[Option[Int]] = barEWF.run.value.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)
  }
}
+5

Source: https://habr.com/ru/post/1599140/


All Articles