Skip to content

Instantly share code, notes, and snippets.

@davidpeklak
Created March 17, 2014 21:01
Show Gist options
  • Save davidpeklak/9608270 to your computer and use it in GitHub Desktop.
Save davidpeklak/9608270 to your computer and use it in GitHub Desktop.
EitherTWriterT
import scalaz._
object WE {
type EA[+A] = (String \/ A)
type WT[+A] = WriterT[EA, Seq[Any], A]
def replace(j: Int)(i: Int): (String \/ Int) = {
if (j > 9) -\/("Failed with " + j.toString)
else \/-(j)
}
val init = \/-(5)
val r1 = init.flatMap(replace(7)).flatMap(replace(10)).flatMap(replace(4))
val initNix: (Seq[Any], EA[Int]) = Seq() -> init
type WA[+A] = WriterT[Id.Id, Seq[Any], A]
def WA[A](t: (Seq[Any], A)) = WriterT[Id.Id, Seq[Any], A](t)
val initW = WA(initNix)
type EWA[+A] = EitherT[WA, String, A]
def EWA[A](wa: WA[EA[A]]) = EitherT[WA, String, A](wa)
val initEW = EWA(initW)
def reWe(j: Int)(i: Int): EWA[Int] = EWA(WA(replace(j)(i).fold(f => Seq(f) -> -\/(f), v => Seq[Any](v) -> \/-(v))))
implicit val seqMonoid: Monoid[Seq[Any]] = new Monoid[Seq[Any]] {
def append(f1: Seq[Any], f2: => Seq[Any]): Seq[Any] = f1 ++ f2
def zero: Seq[Any] = Seq()
}
implicit val WaMonad: Monad[WA] = WriterT.writerTMonad[Id.Id, Seq[Any]]
val r = initEW.flatMap(reWe(7)).flatMap(reWe(8)).flatMap(reWe(10)).flatMap(reWe(4))
val result = r.run.run
}
@gseitz
Copy link

gseitz commented Mar 18, 2014

def reWe2(j: Int)(i: Int): EWA[Int] = {
    replace(j)(i) match {
      case e@ -\/(f) => for {
        _ <- MonadTrans[EWA].liftM(WriterT.tell(Seq(f)))
        x <- EitherT.left(Monad[WA].pure(e))
      } yield x
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment