Home > Software design >  Clojure For loop index numbers
Clojure For loop index numbers

Time:01-30

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.

CodePudding user response:

You need map-indexed:

(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]
       (str x " - " i " - " j))
     (map-indexed (fn [index value] 
                    (str "Index: " index " : " value)))
     (run! println))

Shorter version of (fn [index value] ...):

(map-indexed #(str "Index: " %1" : " %2))

Also consider calling one println with one long string instead of calling 125x println, it seems to be faster:

(->> (for [x numbers
           i colors
           j letters]
       (str x " - " i " - " j))
     (map-indexed #(str "Index: " %1 " : " %2 "\n"))
     str/join
     println)

(str/join is clojure.string/join)

CodePudding user response:

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)))))
  • Related