更新多个键的值

编程入门 行业动态 更新时间:2024-10-24 05:23:44
本文介绍了更新多个键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果您有地图或地图集合,并且想要使用一个函数更新多个键的值,最方便的方式是什么?

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})

更多推荐

更新多个键的值

本文发布于:2023-10-26 11:58:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530068.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!