Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
trait Mutability[F[_]] {
def init[A](a: A): F[Mutability.Var[F, A]]
}
object Mutability {
trait Var[F[_], A] {
def get: F[A]
def put(a: A): F[Unit]
}
implicit val idMutableVar: Mutability[Id] = new Mutability[Id] {
def init[A](a: A): Id[Var[Id, A]] = new Var[Id, A] {
private var value: A = a
def get: Id[A] = a
def put(a: A): Id[Unit] = {
value = a
}
}
}
implicit def syncMutableVar[F[_]: Sync]: Mutability[F] =
new Mutability[F] {
def init[A](a: A): F[Var[F, A]] = {
for {
ref <- Ref.of[F, A](a)
} yield new Var[F, A] {
def get: F[A] = ref.get
def put(a: A): F[Unit] =
ref.set(a)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment