Skip to content

Instantly share code, notes, and snippets.

@ioleo
Last active January 26, 2018 12:13
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 ioleo/c9e3e587176a37558d0c3ef443d2acc7 to your computer and use it in GitHub Desktop.
Save ioleo/c9e3e587176a37558d0c3ef443d2acc7 to your computer and use it in GitHub Desktop.
Simple freestyle free program example with single instruction
import cats.data.State
import freestyle.free._
/* domain objects */
case class Id(id: String)
case class AcmeItem(id: Id)
/* state */
trait MapState[K, V] {
type Type = Map[K, V]
type TypeA[A] = State[Type, A]
def apply(state: Map[K, V]): Type = state
def apply(state: (K, V)*): Type = state.toMap
def empty: Type = Map.empty[K, V]
}
object AcmeStorageState extends MapState[Id, AcmeItem]
/* freestyle free */
@free trait AcmeStorage {
def put(item: AcmeItem): FS[Unit]
def get(id: Id): FS[Option[AcmeItem]]
}
object FreeAcme extends App {
implicit val acmeStorageHandler = new AcmeStorage.Handler[AcmeStorageState.TypeA] {
def put(item: AcmeItem): AcmeStorageState.TypeA[Unit] = State.modify(_.updated(item.id, item))
def get(id: Id): AcmeStorageState.TypeA[Option[AcmeItem]] = State.inspect(_.get(id))
}
val id1 = Id("foo")
val item1 = AcmeItem(id1)
val ops = AcmeStorage.to[AcmeStorage.Op]
val inputState = AcmeStorageState.empty
val program = ops.put(item1)
val outputState = program.interpret[AcmeStorageState.TypeA].runS(inputState).value
val assertion1 = outputState == AcmeStorageState(id1 -> item1)
println("%s << outputState == AcmeStorageState(id1 -> item1)".format(assertion1))
// true << outputState == AcmeStorageState(id1 -> item1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment