Clojure: adding indexes to map vectors
•
Java
I have a vector map I want to associate an index element with each element
Example:
(append-index [{:name "foo"} {:name "bar"} {:name "baz"}])
Should come back
[{:name "foo" :index 1} {:name "bar" :index 2} {:name "baz" :index 3}]
What is the best way to implement the append index function?
Solution
First, clojure starts calculating the vector elements in 0, so you may want to get
[{:index 0,:name "foo"} {:index 1,:name "bar"} {:index 2,:name "baz"}]
You can easily do this with the map indexed function
(defn append-index [coll] (map-indexed #(assoc %2 :index %1) coll))
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码