如何更新一个向量项目在Clojure? [英] How can I update a vector item in Clojure?
本文介绍了如何更新一个向量项目在Clojure?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定:
(def my-vec [{:id 0 :a "foo" :b "bar"} {:id 1 :a "baz" :b "spam"}
{:id 2 :a "qux" :b "fred"}])
如何在my-vec中使用:id = 1
c $ c>:a =baz2和:b =spam2
?
How can I idiomatically update * the item in my-vec with :id=1
to have values :a="baz2"
and :b="spam2"
?
*:我知道,我不会实际更新my-vec,但真正返回一个新的向量,除了替换值,我的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屋!
查看全文