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