user4813927
user4813927

Reputation:

getting values outof a loop (Clojure)

If i make a loop how is it possible to get the values of a variable in standard out by each turn? I am not talking about printing them on the screen, because as long as you are in a loop the values are going back to proceed the loop and not coming out, the only one coming to the standard out is actually the closing value. As an example: (loop [x 0] (if (< x 5) (recur (inc x)) 1234567890))) so i only get the 1234567890 as soon as the loop ends, but i want also 0, 1, 2, 3 and 4 to the std.out.

Upvotes: 3

Views: 146

Answers (2)

Aliaksandr Kazlou
Aliaksandr Kazlou

Reputation: 3301

Maybe a list comprehension for is what you are looking for, or range. For the loop as @zero323 has mentioned you need to use an accumulator.

Upvotes: 1

zero323
zero323

Reputation: 330453

Well, loop is not a loop but a recursion point. If you want to collect all the values you can use some kind of accumulator:

(loop [x 0 acc []]
  (if (< x 5)
    (recur (inc x) (conj acc x))
    (conj acc 1234567890)))

Unless recursion is what you really want some kind of map or for (list comprehension) is probably a better choice.

Upvotes: 3

Related Questions