With a map in Java, you can write map.computeIfAbsent(key, f)that checks if a key already exists on the map, and if it doesnโt call fthe key to generate a value, and enters it on the map. You also have map.putIfAbsent(key, value)one that only puts a value on the card, if the key does not already exist on the card.
Ignoring the fact that Java methods also return a value, and instead need to return a new map, what would be the equivalent code in Clojure?
The best I've come up with so far is to roll my own with something like
(defn compute-if-absent [map key f]
(if (key map)
map
(assoc map key (f key))))
Is there an alternative to rolling my own?
source
share