Update the values of multiple keys

后端 未结 1 823
不知归路
不知归路 2021-01-04 00:33

If you have a map or a collection of maps and you\'d like to be able to update the values of several keys with one function, what the the most idiomatic way of doing this?

相关标签:
1条回答
  • 2021-01-04 01:32

    Whenever you need to iteratively apply a fn to some data, reduce is your friend:

    (defn update-vals [map vals f]
      (reduce #(update-in % [%2] f) map vals))
    

    Here it is in action:

    user> (def m1 {:a 2 :b 3})
    #'user/m1
    user> (update-vals m1 [:a :b] inc)
    {:a 3, :b 4}
    user> (def m [{:a 2 :b 3} {:a 2 :b 5}])
    #'user/m
    user> (map #(update-vals % [:a :b] inc) m)
    ({:a 3, :b 4} {:a 3, :b 6})
    
    0 讨论(0)
提交回复
热议问题