Created
August 19, 2020 06:34
-
-
Save asafch/045db176806cd1e11fcd7f1cc3f165c5 to your computer and use it in GitHub Desktop.
Mimic Java's Map::computeIfAbsent in Clojure
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
(def store (atom {})) | |
(defn nil-protect [f] | |
(fn [m k] | |
(if-let [v' (f k)] | |
(assoc m k v') | |
m))) | |
(defn compute-if-absent [a k f] | |
(let [m (swap! a (nil-protect f) k)] ; in essence: (f m k) | |
(get m k))) | |
(defn do-something [k] | |
(str k k)) | |
(compute-if-absent store :asaf do-something) | |
=> ":asaf:asaf" |
You're right, this snippet is incorrect.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ummm... doesn't work as it intended? it always computes and replaces the value in the atom, even if not absent