Anonymous
Anonymous

Reputation: 153

How to get a 'for' in clojure/lisp to just return the values without creating a list?

In Clojure, running this code:

(for [i (range 5)] i)

creates the list:

(0 1 2 3 4)

But what I'd like the for clause to do would be just to output each of the numbers without creating a list. What do I have to change to achieve this?

Upvotes: 0

Views: 130

Answers (2)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

clojure.core has doseq for just this purpose:

user=> (doseq [i (range 5)] (println i))
0
1
2
3
4
nil

the nil at the end is the repl printing the return value of the doseq call after it finishes processing all the values

Upvotes: 3

Anonymous
Anonymous

Reputation: 153

Since I was trying to get the contents of the list inside of a separate list, what I did to achieve this was wrap the external list with an into clause like so:

(into
  '("original" "list" "contents" ...)
  (for [i (range 5)] i))

Making sure to close off the parentheses for the external list.

Upvotes: 0

Related Questions