Skip to content

Instantly share code, notes, and snippets.

@djspiewak
Created January 6, 2020 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djspiewak/2439165b193ac62a7aca8df2a9eda0d0 to your computer and use it in GitHub Desktop.
Save djspiewak/2439165b193ac62a7aca8df2a9eda0d0 to your computer and use it in GitHub Desktop.
import cats.{Id, MonadError}
import cats.data.Kleisli
import cats.implicits._
import cats.free.FreeT
type F[A] = Kleisli[FreeT[Id, Either[Int, ?], ?], Unit, A]
val F = MonadError[F, Int]
def run[A](fa: F[A]): Either[Int, A] =
fa.run(()).runM(ft => Right(ft))
def map1[A, B](fa: F[A])(f: A => B): F[B] =
fa.map(f)
def map2[A, B](fa: F[A])(f: A => B): F[B] =
fa.flatMap(a => f(a).pure[F])
val eff1 = F.handleErrorWith(map1(F.fromEither(42.asLeft[String]))(_.asRight[Int]))(_.asLeft[String].pure[F])
val eff2 = F.handleErrorWith(map2(F.fromEither(42.asLeft[String]))(_.asRight[Int]))(_.asLeft[String].pure[F])
run(eff1) // => Right(Left(42))
run(eff2) // => Left(42)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment