0
(def m {:a 1 :b 2 :c 3})

Let's say I want each value in m to be incremented. The only way I can think of to do that is

(into {}
      (map
        (fn [[key val]]
          [key (inc val)])
        m))

Is there a better way to do this? I need to do this a lot in my code and it looks kind of hacky. I really do need to use a map here (mostly for O(1) lookups, the key will be a UUID and the value a map), not a vector or a list.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
quantumtremor
  • 3,787
  • 2
  • 17
  • 20
  • this looks related: http://blog.jayfields.com/2011/08/clojure-apply-function-to-each-value-of.html http://stackoverflow.com/questions/9638271/update-the-values-of-multiple-keys – zarkone Mar 15 '15 at 09:01
  • possible duplicate of [Mapping a function on the values of a map in Clojure](http://stackoverflow.com/questions/1676891/mapping-a-function-on-the-values-of-a-map-in-clojure) – Jarlax Mar 15 '15 at 09:09
  • Use fmap, answered previously: http://stackoverflow.com/a/3757598/67957 – Scott B Mar 24 '15 at 20:22

1 Answers1

2

Found something that looks good here: http://clojuredocs.org/clojure.core/reduce-kv.

(defn update-map [m f] 
  (reduce-kv (fn [m k v] 
    (assoc m k (f v))) {} m))

Then you can do

(update-map {:a 1 :b 2} inc)

to get

 {:a 2 :b 3}

If needed you can supply k to f or make a update-key-values function that takes in two functions f and g and applies them to the keys and values respectively.

quantumtremor
  • 3,787
  • 2
  • 17
  • 20