Search code examples
clojure

Clojure loop with count


I am fairly new to Clojure and would help help with some code. I have a function which takes a vector and i would like to loop through the vector and get the value at an index 'i' and the value of 'i' itself. 'i' is the value which is incremented in the loop.

I have checked 'for' at the clojure docs at for and wrote the following code.

(for [i some-vector]
      (print (get-intersec i (.length some-vector) loop-count)))

The loop-count variable is supposed to be the loop count.

I have also checked loop but it does not seem like a feasible solution. Can someone help me with a clojure function i can use or help me write a macro or function that can do that.

Thank you.

Ps: To solve my problem, i use my own counter but would like a better solution.


Solution

  • First, keep in mind that for is for list comprehension, that is, creating new sequences. For looping through a sequence for some side effect, like printing, you probably want to use doseq.

    To include a numeric count with each element as you loop through, you can use map-indexed:

    (def xs [:a :b :c :d])
    
    (doseq [[n elem] (map-indexed #(vector %1 %2) xs)]
      (println n "->" elem))
    

    Output:

    0 -> :a
    1 -> :b
    2 -> :c
    3 -> :d
    

    If you find yourself doing this a lot, like I did, you can create a macro:

    (defmacro doseq-indexed [[[item idx] coll] & forms]
      `(doseq [[~idx ~item] (map-indexed #(vector %1 %2) ~coll)]
         ~@forms))
    

    And use it like this:

    > (doseq-indexed [[n elem] xs] (println n "->" elem))
    0 -> :a
    1 -> :b
    2 -> :c
    3 -> :d