Skip to content

Instantly share code, notes, and snippets.

@justinhj
Created October 4, 2018 19:47
Show Gist options
  • Save justinhj/f9628a758f088e38c3cf8420531f88f5 to your computer and use it in GitHub Desktop.
Save justinhj/f9628a758f088e38c3cf8420531f88f5 to your computer and use it in GitHub Desktop.
Simple example of cats-mtl library
/*
val CatsMTLVersion = "0.4.0"
val CatsVersion = "1.4.0"
val CatsEffectVersion = "1.0.0"
libraryDependencies ++= Seq(
"org.typelevel" %% "cats-core" % CatsVersion,
"org.typelevel" %% "cats-effect" % CatsEffectVersion,
"org.typelevel" %% "cats-mtl-core" % CatsMTLVersion,
*/
import cats._
import cats.data._
import cats.mtl._
import cats.implicits._
import cats.mtl.implicits._
import cats.effect.IO
object MTLFetch {
case class Cat(name: String, yearOfBirth: Int)
val sampleCat1 = Cat("Garfield", 1965)
val sampleCat2 = Cat("Winky", 1973)
type Log = Vector[String]
def program[F[_] : Monad](implicit ft : FunctorTell[F, Log],
aa: ApplicativeAsk[F, Cat]) : F[Int] = {
for(
name <- aa.ask.map(cat => cat.name);
age <- aa.ask.map(cat => cat.yearOfBirth);
_ <- ft.tell(Vector("I did it!"));
_ <- ft.tell(Vector("You did what?"));
_ <- ft.tell(Vector(s"Found the cat called ${name}'s age is $age"))
) yield (2018 - age)
}
def main(args: Array[String]): Unit = {
// Materialize the program with monad transformer instances
val w = program[ReaderT[WriterT[Id, Log, ?], Cat, ?]].run(sampleCat1)
val (log, result) = w.run
println(result, log)
// (53,Vector(I did it!, You did what?, Found the cat called Garfield's age is 1965))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment