Using Clojure Update with Multiple Keys

I am trying to apply a function to all elements on a map that match a specific key.

(def mymap {:a "a" :b "b" :c "c"}) (update-in mymap [:a :b] #(str "X-" %)) 

I expect

 {:a "Xa", :c "c", :b "Xb"} 

But I get

ClassCastException java.lang.String cannot be added to clojure.lang.Associative clojure.lang.RT.assoc (RT.java:702)

Can anybody help me?

+4
source share
3 answers

update-in consists in updating one key on the map (at a certain nesting level [:a :b] means the update key: b inside the key map value: a.

What you can do using the shortcut:

 (reduce #(assoc %1 %2 (str "X-" (%1 %2))) mymap [:a :b]) 
+8
source

Here's a generic function:

 (defn update-each "Updates each keyword listed in ks on associative structure m using fn." [m ks fn] (reduce #(update-in %1 [%2] fn) m ks)) (update-each mymap [:a :b] #(str "X-" %)) 
+1
source

In the haspmap solution below, if it is filtered out first, then it maps to the str function, and then merges with the original hashmap -

 (def m {:a "a" :b "b" :c "c"}) (def keys #{:a :b}) (->> m (filter (fn [[kv]] (k keys))) (map (fn [[kv]] [k (str "X-" v)])) (into {}) (merge m)) 
0
source

All Articles