Last active
April 2, 2017 13:25
-
-
Save yilinwei/8e3e260dc7a0c9ffb2e5518b8d4d5b9f to your computer and use it in GitHub Desktop.
Free example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object MTL { | |
import cats._ | |
import cats.free._ | |
import cats.data._ | |
import cats.implicits._ | |
sealed trait DSL[A] | |
case class Get[A]() extends DSL[A] | |
case class Put[A](a: A) extends DSL[Unit] | |
type PRG[A] = Free[DSL, A] | |
def get[A]: PRG[A] = Free.liftF[DSL, A](Get()) | |
def put[A](a: A): PRG[Unit] = Free.liftF[DSL, Unit](Put(a)) | |
def getEither[A]: PRG[Either[Throwable, A]] = get[A].map(Right(_)) | |
val e = get[Int].liftT[EitherT[?[_], Throwable, ?]] | |
for { | |
x <- e | |
y <- EitherT(getEither[Int]) | |
} yield x + y | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object MTL { | |
import cats._ | |
import cats.free._ | |
import cats.data._ | |
import cats.implicits._ | |
sealed trait DSL[+A] | |
case class Get[A]() extends DSL[Either[Throwable, A]] | |
case class Put[A](a: A) extends DSL[Unit] | |
case class Error(t: Throwable) extends DSL[Nothing] | |
type PRG[A] = Free[DSL, A] | |
def get[A]: PRG[Either[Throwable, A]] = Free.liftF[DSL, Either[Throwable, A]](Get()) | |
def put[A](a: A): PRG[Unit] = Free.liftF[DSL, Unit](Put(a)) | |
def error[A](t: Throwable) : PRG[A] = Free.liftF[DSL, A](Error(t)) | |
for { | |
result <- get[Int].flatMap{ case Right(a) => Free.pure(a); case Left(t) => error(t) } | |
} yield result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment