Skip to content

Instantly share code, notes, and snippets.

@asafch
Created August 19, 2020 06:34
Show Gist options
  • Save asafch/045db176806cd1e11fcd7f1cc3f165c5 to your computer and use it in GitHub Desktop.
Save asafch/045db176806cd1e11fcd7f1cc3f165c5 to your computer and use it in GitHub Desktop.
Mimic Java's Map::computeIfAbsent in Clojure
(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"
@asafch
Copy link
Author

asafch commented Nov 7, 2022

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