Clojure 中集合的更新?
我的集合中有一系列项目,如下所示:
(def my-set
#{
{:id "ab" :a 1 :b 2}
{:id "abc" :a 1 :b 2}
{:id "abcd" :a 1 :b 2}
}
)
: 我希望更新其中一个项目,如下所示:
(update-in-set my-set :id "abc" {:id "abc" :a 6 :b 20})
。会返回::
#{
{:id "ab" :a 1 :b 2}
{:id "abc" :a 6 :b 20}
{:id "abcd" :a 1 :b 2}
}
有没有 Clojure 内置函数或其他简单的方法来做到这一点?
更新
最后我这样做了:
(defn update-in-set [my-set key value new-record]
(merge (clojure.set/select #(not= (get % key) value) my-set ) new-record)
)
i have a series of items in a set like this:
(def my-set
#{
{:id "ab" :a 1 :b 2}
{:id "abc" :a 1 :b 2}
{:id "abcd" :a 1 :b 2}
}
)
: and I wish to update one of the items something like this :
(update-in-set my-set :id "abc" {:id "abc" :a 6 :b 20})
. that would return :
#{
{:id "ab" :a 1 :b 2}
{:id "abc" :a 6 :b 20}
{:id "abcd" :a 1 :b 2}
}
: Is there any Clojure built in function or other easy way to do this?
Update
In the end I did this:
(defn update-in-set [my-set key value new-record]
(merge (clojure.set/select #(not= (get % key) value) my-set ) new-record)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想知道你是否不应该在这里使用地图而不是集合,以 id 作为键。然后您想要做的事情就可以使用
assoc
轻松执行。您遇到了问题,因为集合实际上没有更新值的想法 - 每个项目都是唯一的,并且存在或不存在 - 因此您需要做的是删除旧值并添加新值。使用 conj 和 disj 可以更轻松地完成此操作,我认为:
这会删除 'a 并添加 'e。这假设您有某种方式从“钥匙”获取完整的项目。
I wonder if you shouldn't be using a map rather than a set here, with id as the key. Then what you want to do could be easily performed with
assoc
.You are having problems as sets don't really have the idea of updating values - each item is unique and either present or not - so what you need to do is remove the old value and add a new one. This could be done a little easier with
conj
anddisj
I think:Which would remove 'a and add 'e. This assumes you have some way of getting the complete item from the "key".