如何在 Clojure 中更新矢量项? [英] How can I update a vector item in Clojure?

查看:11
本文介绍了如何在 Clojure 中更新矢量项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定:

(def my-vec [{:id 0 :a "foo" :b "bar"} {:id 1 :a "baz" :b "spam"} 
             {:id 2 :a "qux" :b "fred"}])

如何用 :id=1 习惯性地更新 * my-vec 中的项目,使其具有值 :a="baz2":b=垃圾邮件2"?

How can I idiomatically update * the item in my-vec with :id=1 to have values :a="baz2" and :b="spam2"?

*:我意识到我实际上不会更新 my-vec,而是真正返回一个与 my-vec 相同的新向量,除了替换值.

推荐答案

在映射向量上映射一个函数,如果键匹配则创建修改后的映射,或者如果键不匹配则使用原始映射然后转换结果回到向量中

map a function over the vector of maps that either creates a modified map if the key matches or uses the original if the keys don't match then turn the result back into a vector

(vec (map #(if (= (:id %) 1) 
             (assoc % :a "baz2" :b "spam2")
             %)))

虽然这确实显示了结构共享发生的位置,但可以更简洁地做到这一点.

It is possible to do this more succinctly though this one really shows where the structural sharing occurs.

这篇关于如何在 Clojure 中更新矢量项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆