Last active
January 23, 2019 08:48
-
-
Save ioleo/faa3ab10b271786033f48618bd96b386 to your computer and use it in GitHub Desktop.
Freestyle tagless program example with multiple algebras composed into module
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.effect.IO | |
import freestyle.tagless._ | |
@tagless trait Logger { | |
def debug(message: String): FS[Unit] | |
} | |
@tagless trait Summer { | |
def sum(a: Int, b: Int): FS[Int] | |
} | |
@module trait TaglessApp { | |
// necessary boilerplate to provide map/flatmap syntax on log/summer for the for comprehension | |
implicit val M: Monad[FS] | |
import cats.implicits._ | |
val log: Logger | |
val summer: Summer | |
def program(a: Int, b: Int): FS[Int] = | |
for { | |
sum <- summer.sum(a, b) | |
_ <- log.debug(s"$a + $b = $sum") | |
} yield sum | |
} | |
object TaglessModulesExample extends App { | |
implicit val loggerHandler = new Logger.Handler[IO] { | |
def debug(message: String): IO[Unit] = IO { println(s"Logger debug: $message") } | |
} | |
implicit val summerHandler = new Summer.Handler[IO] { | |
override def sum(a: Int, b: Int): IO[Int] = IO { a + b } | |
} | |
val result = TaglessApp.to[IO].program(5, 3).unsafeRunSync() | |
println(s"Result is: $result") | |
// Logger debug: 5 + 3 = 8 | |
// Result is: 8 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment