Skip to content

Instantly share code, notes, and snippets.

@Leammas
Last active March 3, 2017 09:34
Show Gist options
  • Save Leammas/fa3f508eead9d3dd096a846bdc7765b9 to your computer and use it in GitHub Desktop.
Save Leammas/fa3f508eead9d3dd096a846bdc7765b9 to your computer and use it in GitHub Desktop.
import cats.Id
import cats.free.Free
import freestyle._
import freestyle.implicits._
import cats.implicits._
object Main extends App {
case class Foo(id: Int, content: String)
@free
trait CrudActions[F[_]] {
def create(a: Foo): FreeS[F, Int]
def read(id: Int): FreeS[F, Foo]
def update(a: Foo): FreeS[F, Unit]
def delete(id: Int): FreeS[F, Unit]
}
@free
trait SumActions[F[_]] {
def concat(a: Foo, b: Foo): FreeS[F, Foo]
def sum(a: Foo, b: Foo): FreeS[F, Foo]
}
@free
trait FooReader[F[_]] {
def getFoo: FreeS[F, Foo]
}
@module
trait Application[F[_]] {
val crud: CrudActions[F]
val sum: SumActions[F]
val reader: FooReader[F]
}
def program[F[_]](implicit A: Application[F]): FreeS[F, List[Foo]] = {
import A._
for {
f <- reader.getFoo
id <- crud.create(f)
created <- crud.read(id)
_ <- crud.update(created.copy(content = "bar"))
updated <- crud.read(id)
concated <- sum.concat(created, updated)
summed <- sum.sum(created, updated)
} yield List(concated, summed)
}
implicit val idCrud = new CrudActions.Interpreter[Id] {
var store = Map.empty[Int, Foo]
var ai = 1
def createImpl(a: Foo): Id[Int] = {
val aId = a.copy(id = ai)
store = store + (ai -> aId)
ai = ai + 1
aId.id
}
def readImpl(id: Int): Id[Foo] = store(id)
def updateImpl(a: Foo): Id[Unit] = {
store = store.updated(a.id, a)
()
}
def deleteImpl(id: Int): Id[Unit] = {
store = store - id
()
}
}
implicit val idSum = new SumActions.Interpreter[Id] {
def concatImpl(a: Foo, b: Foo): Id[Foo] = Foo(a.id, a.content + b.content)
def sumImpl(a: Foo, b: Foo): Id[Foo] = Foo(a.id + b.id, a.content)
}
implicit val idReader = new FooReader.Interpreter[Id] {
def getFooImpl = Foo(-100, "content")
}
val freeProgResult = program[Application.T].exec[Id]
assert {
freeProgResult == List(Foo(1, "contentbar"), Foo(2, "content"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment