To update multiple values, you can also take advantage of reducing taking an already filled battery and applying a function to this and each member of the next collection.
=> (reduce (fn [ak] (update-in ak inc)) {:a 1 :b 2 :c 3 :d 4} [[:a] [:c]]) {:a 2, :c 4, :b 2, :d 4}
Keep in mind the keys you need to wrap in vectors, but you can still perform several updates in nested structures, such as the original update.
If you made this a generic function, you can automatically wrap the vector over the key by checking it with coll ?:
(defn multi-update-in [mvf & args] (reduce (fn [acc p] (apply (partial update-in acc (if (coll? p) p (vector p)) f) args)) mv))
which allows you to receive single-level / key updates without the need to wrap keys in vectors
=> (multi-update-in {:a 1 :b 2 :c 3 :d 4} [:a :c] inc) {:a 2, :c 4, :b 2, :d 4}
but you can still perform nested updates
(def people {"keith" {:age 27 :hobby "needlefelting"} "penelope" {:age 39 :hobby "thaiboxing"} "brian" {:age 12 :hobby "rocket science"}}) => (multi-update-in people [["keith" :age] ["brian" :age]] inc) {"keith" {:age 28, :hobby "needlefelting"}, "penelope" {:age 39, :hobby "thaiboxing"}, "brian" {:age 13, :hobby "rocket science"}}
Nielsk
source share