Alex Rivera | Logout

Clojure: Call a function for each element in a vector with it index

Asked 2009-10-30T17:51:45.657
27

Say I have a vector:

(def data ["Hello" "World" "Test" "This"])

And I want to populate a table somewhere that has an api:

(defn setCell
  [row col value]
  (some code here))

Then what is the best way to get the following calls to happen:

(setCell 0 0 "Hello")
(setCell 0 1 "World")
(setCell 0 2 "Test")
(setCell 0 3 "This")

I found that the following will work:

(let [idv (map vector (iterate inc 0) data)]
  (doseq [[index value] idv] (setCell 0 index value)))

But is there a faster way that does not require a new temporary datastructure idv?

Edit
Report

1 Answer

28

A bit late in the game but for people accessing this page: there is now (since clojure 1.2) a map-indexed function available in clojure.core.

One issue (unless I'm mistaken): there's no "pmap" equivalent, meaning that map-indexed computations cannot easily be parallelized. In that case, I'd refer to solutions offered above.

answered 2011-05-13T13:28:54.557

Your Answer