Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Last active February 18, 2019 12:59
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/b4e0551c3ad8e1744e74b138a03e2b4b to your computer and use it in GitHub Desktop.
Save yasuabe/b4e0551c3ad8e1744e74b138a03e2b4b to your computer and use it in GitHub Desktop.
minimal cake + tagless final + free monad
import cats.free.Free
import cats.free.Free.liftF
import cats.~>
// 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]
trait MovieRepo[F[_]] {
def getMovie(id: Int): F[Option[Movie]]
}
trait UsesMovieRepo[F[_]] {
val movieRepo: MovieRepo[F]
}
trait MovieService[F[_]] extends UsesMovieRepo[F] {
def getMovie(id: Int): F[Option[Movie]] = movieRepo.getMovie(id)
}
object MovieRepoImpl extends MovieRepo[QueryF] {
def getMovie(id: Int): QueryF[Option[Movie]] = liftF(GetMovie(id))
}
trait MixInMovieRepo {
val movieRepo: MovieRepo[QueryF] = MovieRepoImpl
}
object MovieServiceImpl extends MovieService[QueryF] with MixInMovieRepo
// 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 = MovieServiceImpl.getMovie(42).foldMap(taskInterpreter)
// runtime ------------------------------------------------------
import scala.concurrent.Await
import scala.concurrent.duration._
import monix.execution.Scheduler.Implicits.global
Await.result(program.runToFuture, 1.second)
//res0: Option[Movie] = Some(Movie(42,A Movie))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment