Created
April 7, 2019 15:14
-
-
Save yasuabe/d6505e7df9d4e4bbe74c675359bd8a0c to your computer and use it in GitHub Desktop.
sample code for Cats MTL MonadState
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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