开发者

update-in for sets in Clojure?

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


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 and disj I think:

(conj (disj #{'a 'b 'c} 'a) 'e)

Which would remove 'a and add 'e. This assumes you have some way of getting the complete item from the "key".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜