本文介绍了更新多个键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果您有地图或地图集合,并且想要使用一个函数更新多个键的值,最方便的方式是什么?
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?
=> (def m [{:a 2 :b 3} {:a 2 :b 5}]) #'user/m => (map #(update-in % [:a] inc) m) ({:a 3, :b 3} {:a 3, :b 5})我不想映射每个键的更新,我理想地喜欢一些操作如下的函数:
Rather than mapping update-in for each key, I'd ideally like some function that operates like this:
=> (map #(update-vals % [:a :b] inc) m) ({:a 3, :b 4} {:a 3, :b 6})任何建议都非常感谢!我试图减少不必要的长脚本中的行数。
Any advice would be much appreciated! I'm trying to reduce the number of lines in an unnecessarily long script.
推荐答案每当你需要迭代应用fn一些数据 reduce 是您的朋友:
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))b $ b
这里是操作中:
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})更多推荐
更新多个键的值
发布评论