How to implement a For loop in Clojure

One way to translate an imperative for loop to Clojure is to use the for macro.

(for [i (range 10)] (inc i))

The above function will return all the numbers from 0 to 9 incremented by 1. However, it appears you simply want to iterate over a sequential collection and use each item. If that’s all that you need, then you don’t need to reference an index value, instead you can reference each item directly.

(for [d my-vec-of-data] (my-function d))

However, for this simple case, the map function would probably be a better choice because it is designed to invoke functions with arguments from collections. The following example is equivalent to the use of for above.

(map my-function my-vec-of-data)

Both map and for return a collection of values made up of the values returned by my-function. This is because Clojure’s data structures are immutable, so it’s necessary to have a new collection returned. If that isn’t what you need or if your function has side effects, you could use doseq instead of for, which returns nil.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)