Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update-in for sets in Clojure?

Tags:

set

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)
)
like image 292
yazz.com Avatar asked Feb 22 '26 10:02

yazz.com


1 Answers

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".

like image 66
Adrian Mouat Avatar answered Feb 25 '26 08:02

Adrian Mouat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!