Created
January 26, 2018 12:19
-
-
Save ioleo/1a870df8dc8384bec1691990614d0710 to your computer and use it in GitHub Desktop.
Simple freestyle tagless program example with single instruction
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.data.State | |
import freestyle.tagless._ | |
/* 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 tagless */ | |
@tagless trait AcmeStorage[F[_]] { | |
def put(item: AcmeItem): F[Unit] | |
def get(id: Id): F[Option[AcmeItem]] | |
} | |
object TaglessAcme 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[AcmeStorageState.TypeA] | |
val inputState = AcmeStorageState.empty | |
val program = ops.put(item1) | |
val outputState = program.run(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