Created
September 28, 2021 09:56
-
-
Save ghik/3584c0993e54a17b427e428223f50618 to your computer and use it in GitHub Desktop.
Tagless Final na kolanie
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._ | |
| import cats.effect.IO | |
| import cats.implicits._ | |
| case class UserId(value: String) extends AnyVal | |
| case class User(id: UserId, name: String, age: Int) | |
| trait DbApi[F[_]] { | |
| def load(id: UserId): F[Option[User]] | |
| def save(user: User): F[Unit] | |
| } | |
| object DbApi { | |
| def apply[F[_]](implicit dbApi: DbApi[F]): DbApi[F] = dbApi | |
| } | |
| trait Console[F[_]] { | |
| def napisz(any: Any): F[Unit] | |
| } | |
| object Console { | |
| def apply[F[_]](implicit console: Console[F]): Console[F] = console | |
| } | |
| object TaglessFinalFantasy { | |
| def program[F[_] : DbApi : Console : Monad](userId: UserId): F[Unit] = for { | |
| _ <- Monad[F].unit | |
| user = User(userId, "Fred", 42) | |
| _ <- DbApi[F].save(user) | |
| _ <- Console[F].napisz("rób") | |
| } yield () | |
| implicit object catsEffectDbApi extends DbApi[IO] { | |
| private val db = new MHashMap[UserId, User] | |
| override def load(id: UserId): IO[Option[User]] = IO(db.get(id)) | |
| override def save(user: User): IO[Unit] = IO(db(user.id) = user) | |
| } | |
| implicit object catsEffectConsole extends Console[IO] { | |
| def napisz(any: Any): IO[Unit] = IO.apply(println(any)) | |
| } | |
| val ioProgram = program[IO](UserId("fredid")) | |
| type Id[+T] = T | |
| implicit object syncDbApi extends DbApi[Id] { | |
| private val db = new MHashMap[UserId, User] | |
| override def load(id: UserId): Option[User] = db.get(id) | |
| override def save(user: User): Unit = { | |
| db(user.id) = user | |
| } | |
| } | |
| implicit object syncConsole extends Console[Id] { | |
| override def napisz(any: Any): Id[Unit] = println(any) | |
| } | |
| def main(args: Array[String]): Unit = { | |
| program[Id](UserId("fredid")) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment