Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created April 7, 2019 15:24
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/4af03c59a51601bcd7c2bc8c8ada21ca to your computer and use it in GitHub Desktop.
Save yasuabe/4af03c59a51601bcd7c2bc8c8ada21ca to your computer and use it in GitHub Desktop.
sample code for monad transformer
import cats.data.{EitherT, State, StateT}
import cats.instances.either._
object A {
type SET[E, S, R] = StateT[Either[E, ?], S, R]
type EST[E, S, R] = EitherT[State[S, ?], E, R]
def decrementSE: SET[String, Int, Unit] = for {
x <- StateT.get[Either[String, ?], Int]
_ <- if (x > 0) StateT.set[Either[String, ?], Int](x - 1)
else StateT.liftF[Either[String, ?], Int, Unit](Left("error"))
} yield ()
def decrementES: EST[String, Int, Unit] = for {
x <- EitherT.liftF[State[Int, ?], String, Int](State.get[Int])
_ <- if (x > 0) EitherT.liftF[State[Int, ?], String, Unit](State.set(x - 1))
else EitherT.leftT[State[Int, ?], Unit]("error")
} yield ()
def runSE(n: Int): Either[String, (Int, Unit)] =
decrementSE.run(n)
def runES(n: Int): (Int, Either[String, Unit]) =
decrementES.value.run(n).value
}
A.runSE(0) // Left(error)
A.runSE(1) // Right((0,()))
A.runES(0) // (0,Left(error))
A.runES(1) // (0,Right(()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment