Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created April 7, 2019 15:17
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/84aebc6cdbf3239ea68831e301fecbab to your computer and use it in GitHub Desktop.
Save yasuabe/84aebc6cdbf3239ea68831e301fecbab to your computer and use it in GitHub Desktop.
sample code for Cats MTL FunctorListen
import cats.{FlatMap, Monad}
import cats.data.{Chain, WriterT}
import cats.effect.{IO, Sync}
import cats.syntax.flatMap._
import cats.syntax.functor._
import cats.mtl.syntax.listen._
import cats.mtl.{FunctorListen, FunctorTell}
import Chain.one
type Logs = Chain[String]
def tellFunc[F[_]: FlatMap: Sync](n: Int)(implicit F: FunctorTell[F, Logs]): F[Unit] =
for {
_ <- F.tell(one("begin"))
_ <- Sync[F].delay { println(s"n = $n") }
_ <- F.tell(one("end"))
} yield ()
def send[F[_]: Sync](logs: Logs): F[Unit] =
Sync[F].delay { println(s"Sending to log server: $logs") }
import cats.mtl.instances.listen._
def program[F[_]: Sync: λ[F[_] => FunctorListen[F, Logs]]](n: Int) =
tellFunc[F](n).listen >>= { case (_, logs) =>
send[F](logs)
}
program[WriterT[IO, Logs, ?]](12345).run.unsafeRunSync()
// n = 12345
// Sending to log server: Chain(begin, end)
// res0: (cats.data.Chain[String], Unit) = (Chain(begin, end),())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment