Created
February 15, 2019 10:35
-
-
Save jilen/317aae496d73f06c33ceaab7582b679b to your computer and use it in GitHub Desktop.
A thread safe map using cats-effect
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
import cats._ | |
import cats.effect._ | |
import cats.effect.concurrent._ | |
import cats.syntax.all._ | |
class SafeMap[F[_], K, V](ref: Ref[F, Map[K, V]])(implicit F: Functor[F]) { | |
def putIfAbsent(k: K, v: V): F[Option[V]] = ref.modify { m => | |
m.get(k) match { | |
case None => | |
(m + (k -> v), None) | |
case Some(v) => | |
(m, Some(v)) | |
} | |
} | |
def remove(k: K, old: V): F[Boolean] = ref.modify { m => | |
m.get(k) match { | |
case Some(v) if v == old => | |
(m - k, true) | |
case _ => (m, false) | |
} | |
} | |
def get(k: K): F[Option[V]] = ref.get.map(_.get(k)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment