Mapping over a vector performing side-effects

To add to Justin's answer, doseq is a macro, and thus carries with it all the limitations of macros.

I would write a foreach function that internally uses doseq.

user=> (defn foreach [f xs] (doseq [x xs] (f x)))
#'user/foreach

user=> (foreach println [11 690 3 45])
11
690
3
45
nil

map is lazy and won't realize results unless you ask for them. If you want to perform a side effect for each element in a sequence, and don't care about the return value, use doseq:

;; returns nil, prints each line
(doseq [line vector-of-lines]
  (println line))

If you do care about the return value, use (doall):

;; returns a sequence of nils, prints each line
(doall (map println vector-of-lines))

(dorun (map println vector-of-lines))

dorun forces the evaluation of the lazy sequence, but also discards the individual results of each of item in the sequence. This is perfect for sequences that are purely for side-effects which is exactly what you want here.

Tags:

Clojure