Search code examples
for-loopindexingclojure

Clojure For loop index numbers


How can I have the index of this for loop in this block of code:

(def numbers [:one :two :three :four :five])
(def colors  [:green :red :blue :pink :yellow])
(def letters [:A :B :C :D :E])

(for [x numbers
      i colors
      j letters]
    (println (str x " - " i " - " j)))

This code will print 125 lines and I want to have the index number with each line.


Solution

  • Using atoms are discouraged in Clojure, but I think this is the simplest way:

    (let [index (atom 0)]
      (for [x numbers
            i colors
            j letters]
        (do (swap! index inc)
            (println (str @index ": " x " - " i " - " j)))))