24

Implementing a for loop in clojure seems to be easy, but how can I implement a foreach statement that reads each element in the list(vector) and does something?

like this...

(foreach i list expression)

Thanks in advance!

1
  • 1
    What about map: (map (fn [i] …) list)? Commented Mar 12, 2011 at 22:13

2 Answers 2

32

Just replace for with doseq and you're all set. Don't use map, which is just as lazy as for.

Sign up to request clarification or add additional context in comments.

2 Comments

More precisely: (doseq [i list] expression)
Thanks, Alex. I figured my answer was sufficient since he already knows how to use for, but of course people may wind up reading this who don't.
0

map is the functional equivalent of foreach, whereas doseq is for imperative programming with side-effects.

map takes a function f and a seqable collection coll and returns the lazily-evaluated result of applying f to each element in the collection.

Example:

(map inc [1 2 3 4])
=> (2 3 4 5)

(map (fn [x] (* x 2)) [1 2 3 4])
=> (2 4 6 8)

(map dec (take 5 (range)))
=> (-1 0 1 2 3)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.