tags:

views:

94

answers:

2

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

+5  A: 

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)))
bugspy.net
Ah! Your second function is exactly what I was trying to do with the laziness. Thank you!
scrotty
+5  A: 

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))
Brian Carper
Thank you, Brian. I wish I could award two right answers. Bugspy.net's accomplishes exactly what I'm looking for, but I am keeping yours in mind if true uniqueness becomes important.
scrotty