Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Last active Feb 19, 2019
Embed
What would you like to do?
oop to fp - free monad
import cats.free.Free.liftF
import cats.free.Free
import cats.{Id, ~>}
// domain layer -----------------------------------------------------------
case class Movie(id: Int, title: String)
sealed trait Query[A]
case class GetMovie(id: Int) extends Query[Option[Movie]]
type QueryF[T] = Free[Query, T]
object MovieRepoOps {
def getMovie(id: Int): QueryF[Option[Movie]] = liftF(GetMovie(id))
}
object MovieService {
def getMovie(id: Int): QueryF[Option[Movie]] = for {
movie <- MovieRepoOps.getMovie(id)
} yield movie
}
// application layer ------------------------------------------------------
import monix.eval.Task
val db = Map[Int, Movie](42 -> Movie(42, "A Movie"))
def taskInterpreter: Query ~> Task = new (Query ~> Task) {
def apply[A](fa: Query[A]): Task[A] = fa match {
case GetMovie(id) => Task(db.get(id))
}
}
val program = MovieService.getMovie(42).foldMap(taskInterpreter)
// rumtime layer -------------------------------------------------
import scala.concurrent.Await
import monix.execution.Scheduler.Implicits.global
import scala.concurrent.duration._
Await.result(program.runToFuture, 1.second)
// Some(Movie(42, A Movie))
// test environment -------------------------------------------------------
def testInterpreter: Query ~> Id = new (Query ~> Id) {
def apply[A](fa: Query[A]): Id[A] = fa match {
case GetMovie(_: Int) => Option(Movie(-1, "Test"))
}
}
val id1 = MovieService.getMovie(42).foldMap(testInterpreter)
// Some(Movie(-1,Test))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment