In Clojure how could I create an "add id to map" function?
Say I have a collection of maps:
(def coll #{{:name "foo"} {:name "bar"}})
I want a function that will add an id (a unique number is fine) to each map element in the collection. i.e.
#{{:id 1 :name "foo"} {:id 2 :开发者_运维百科name "bar"}}
The following DOES NOT WORK, but it's the line of thinking I currently have.
(defn add-unique-id [coll]
(map assoc :id (iterate inc 0) coll))
Thanks in advance...
If you want to be really, really sure the IDs are unique, use UUIDs.
(defn add-id [coll] (map #(assoc % :id (str (java.util.UUID/randomUUID))) coll))
How about
(defn add-unique-id [coll]
(map #(assoc %1 :id %2) coll (range (count coll))))
Or
(defn add-unique-id [coll]
(map #(assoc %1 :id %2) coll (iterate inc 0)))
精彩评论