Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Clojure how could I create an "add id to map" function?

Tags:

map

clojure

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

like image 968
scrotty Avatar asked Feb 14 '10 21:02

scrotty


2 Answers

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))
like image 107
Brian Carper Avatar answered Sep 28 '22 13:09

Brian Carper


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)))
like image 36
GabiMe Avatar answered Sep 28 '22 13:09

GabiMe