What is equivalent to Java computeIfAbsent or putIfAbsent in Clojure?

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?

+4
source share
3 answers
Cards

Clojure , - , . , , , .

compute-if-absent . , , {false 1}. if contains? key:

(defn compute-if-absent [m k f]
  (if (contains? m k)
    m
    (assoc m key (f k))))

, ConcurrentMap, Java interop Clojure.

+4

merge put-if-absent:

(merge {key val} m)

compute-if-absent, , , (f key) m:

(merge {key (f key)} m)
+2

If you are trying to implement some form of caching, you can use the clojure great function memoize.

Example: (def fast-inc (memoize inc))

See: http://clojuredocs.org/clojure.core/memoize

0
source

All Articles