In Clojure, how can I create the "add identifier to map" function?

Say I have a set of cards:

(def coll #{{:name "foo"} {:name "bar"}})

I need a function that will add an id (a unique number in order) to each card element in the collection. i.e.

#{{:id 1 :name "foo"} {:id 2 :name "bar"}}

The following DOES NOT WORK, but this is the line of thinking that I now have.

(defn add-unique-id [coll]
(map assoc :id (iterate inc 0) coll))

Thanks in advance...

+5
source share
2 answers

What 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)))
+8
source

If you want to be really, really sure that the identifiers are unique, use the UUID .

(defn add-id [coll]
  (map # (assoc%: id (str (java.util.UUID / randomUUID))) coll))
+11
source

All Articles