If I have:
import scala.concurrent._
import scalaz._, Scalaz._
type Z = List[String]
type F[α] = Future[α]
type WT[α] = WriterT[F, Z, α]
implicit val z: Monoid[Z] = new Monoid[Z] {
def zero = Nil
def append (f1: Z, f2: => Z) = f1 ::: f2
}
implicit val f: Monad[F] = scalaz.std.scalaFuture.futureInstance
I can write code like this:
def fooA (): WT[Int] = WriterT.put[F, Z, Int] (f.point (18))(z.zero)
def fooB (): WT[Int] = WriterT.put[F, Z, Int] (f.point (42))(z.zero)
def fooLog (msg: String): WT[Unit] = WriterT.put[F, Z, Unit] (f.point (()))(msg :: Nil))
def foo (): WT[Int] = for {
_: Unit <- fooLog ("log #1")
a: Int <- fooA
_: Unit <- fooLog ("log #2")
b: Int <- fooB
_: Unit <- fooLog ("log #3")
} yield a + b
Suppose I define:
type WTT[α] = WriterT[Future, Z, Throwable \/ α]
def flakeyInt (i: Int): Throwable \/ Int = new java.util.Random().nextBoolean match {
case false => i.right
case true => new Exception (":-(").left
}
I can then write this:
def barA (): WTT[Int] = WriterT.put[F, Z, Throwable \/ Int] (f.point (flakeyInt (18)))(z.zero)
def barB (): WTT[Int] = WriterT.put[F, Z, Throwable \/ Int] (f.point (flakeyInt (42)))(z.zero)
def barLog (msg: String): WTT[Unit] = WriterT.put[F, Z, Throwable \/ Unit] (f.point (().right))(msg :: Nil))
def bar (): WTT[Int] = for {
_: Throwable \/ Unit <- barLog ("log #1")
x: Throwable \/ Int <- barA
_: Throwable \/ Unit <- barLog ("log #2")
y: Throwable \/ Int <- barB
_: Throwable \/ Unit <- barLog ("log #3")
} yield {
for {
a <- x
b <- y
} yield a + b
}
Is there a way to make the <-
in the for-yield return type α
, not \/[Throwable, α]
so I don't have to manually flatten the Throwables at the end? Ideally I would like to make the bar
function look like the foo
function so that I can hide flattening the errors from the logic.
Follow up question:
Customising composition of Future, Either and Writer in Scalaz