Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created April 7, 2019 15:14
Show Gist options
  • Save yasuabe/d6505e7df9d4e4bbe74c675359bd8a0c to your computer and use it in GitHub Desktop.
Save yasuabe/d6505e7df9d4e4bbe74c675359bd8a0c to your computer and use it in GitHub Desktop.
sample code for Cats MTL MonadState
import cats.Monad
import cats.data.StateT
import cats.effect.{IO, Sync}
import cats.mtl.MonadState
import cats.syntax.show._
import cats.instances.int._
import cats.syntax.flatMap._
import cats.syntax.functor._
import cats.syntax.applicative._
import cats.syntax.traverse._
import cats.instances.list._
import cats.mtl.instances.state._
type Cache = Map[Int, Int]
def triple[F[_]: Sync](n: Int): F[Int] =
Sync[F].delay { println(show"triple($n)") } as (n * 3)
def tripleWithCache[F[_]: Monad: Sync](n: Int)(implicit F: MonadState[F, Cache]): F[Int] =
for {
memo <- F.get
value <- memo.get(n) match {
case Some(v) => v.pure[F]
case None => triple[F](n) >>= { v => F.modify(_.updated(n, v)) as v }
}
} yield value
List(1, 3, 1, 2, 3)
.traverse(tripleWithCache[StateT[IO, Cache, ?]])
.run(Map(3 -> 9))
.unsafeRunSync()
// triple(1)
// triple(2)
// (Map(3 -> 9, 1 -> 3, 2 -> 6), List(3, 9, 3, 6, 9))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment