Created
November 3, 2018 18:39
-
-
Save YBogomolov/93d500003673dcc25b8a65b759b88432 to your computer and use it in GitHub Desktop.
Tagless Final example in Scala + Cats
This file contains 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 scala.language.higherKinds | |
import cats._ | |
import cats.implicits._ | |
final case class User(id: Integer, name: String, age: Integer, isAdmin: Boolean) | |
val fakeUsers: List[User] = List( | |
User(1, "John Connor", 32, false), | |
User(2, "John Smith", 18, false), | |
User(3, "Mark Brian", 28, false) | |
) | |
trait UserOps[F[_]] { | |
def search(name: String): F[List[User]] | |
def makeAdmin(users: List[User]): F[List[User]] | |
def save(users: List[User]): F[List[Boolean]] | |
} | |
object identityInterpreter extends UserOps[Id] { | |
def search(name: String): Id[List[User]] = | |
fakeUsers.filter(u => u.name contains name) | |
def makeAdmin(users: List[User]): Id[List[User]] = | |
users.map(u => u.copy(isAdmin = true)) | |
def save(users: List[User]): Id[List[Boolean]] = users.map(_.isAdmin) | |
} | |
def program[F[_]: Monad](F: UserOps[F]) = | |
for { | |
johns <- F.search("John") | |
admins <- F.makeAdmin(johns) | |
res <- F.save(admins) | |
} yield res | |
print(program(identityInterpreter)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment