Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created April 7, 2019 15:25
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 yasuabe/2ee7df9f7d1a6cc62e3efa12d65f8fc0 to your computer and use it in GitHub Desktop.
Save yasuabe/2ee7df9f7d1a6cc62e3efa12d65f8fc0 to your computer and use it in GitHub Desktop.
sample code for Cats MTL
import cats.data.{EitherT, State, StateT}
import cats.Monad
import cats.syntax.flatMap._
import cats.syntax.functor._
import cats.instances.either._
import cats.mtl.{FunctorRaise, MonadState}
import MonadState._
import FunctorRaise._
type MSI[F[_]] = MonadState[F, Int]
type FRS[F[_]] = FunctorRaise[F, String]
def decr[F[_]: Monad: MSI: FRS]: F[Unit] = for {
x <- get
_ <- if (x > 0) set(x - 1) else raise("error")
} yield ()
object M {
import cats.mtl.implicits._
type SET[R] = StateT[Either[String, ?], Int, R]
type EST[R] = EitherT[State[Int, ?], String, R]
def runSE(n: Int): Either[String, (Int, Unit)] = decr[SET].run(n)
def runES(n: Int): (Int, Either[String, Unit]) = decr[EST].value.run(n).value
}
M.runSE(0) // Left(error)
M.runSE(1) // Right((0,()))
M.runES(0) // (0,Left(error))
M.runES(1) // (0,Right(()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment