Skip to content

Instantly share code, notes, and snippets.

@chuwy
Created November 10, 2019 15:52
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 chuwy/1854efe7a70a7344f22c102a39266113 to your computer and use it in GitHub Desktop.
Save chuwy/1854efe7a70a7344f22c102a39266113 to your computer and use it in GitHub Desktop.
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