Retrieving values โ€‹โ€‹from a loop (Clojure)

If I create a loop, how can I get the values โ€‹โ€‹of the variable in the standard for each turn? I'm not talking about printing them to the screen because while you are in the loop, the values โ€‹โ€‹come back to continue the loop rather than quit, the only one that comes to standard is actually the closure value. As an example: (loop [x 0] (if (< x 5) (recur (inc x)) 1234567890)))

so I only get 1234567890 as soon as the loop ends, but I also want 0, 1, 2, 3 and 4 in std.out.

+3


source to share


2 answers


Well, loop

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 the recursion means that you really want some type map

or for

(list comprehension) it is probably the best choice.

+3


source


Maybe list comprehension for

is what you are looking for, or range

. For loop

, as @ zero323 pointed out, you need to use a battery.



+1


source







All Articles