1

Given a vector, or possibly nested vector, how do you iterate a function in Clojure over the vector (nested vector) n times? Moreover, how can you output each level of iteration into a vector? Whereby the output vector starts with the initial conditions, namely the input vector (nested vector), followed by the subsequent iterations.

1 Answer 1

2

I think what you want is iterate. It returns a lazy sequence of the iterations, starting with the input. So, for example:

(def init (range 10))

(take 3 (iterate #(map inc %) init)) 
;; gives ((0 1 2 3 4 5 6 7 8 9) (1 2 3 4 5 6 7 8 9 10) (2 3 4 5 6 7 8 9 10 11))
2
  • How could this be turned into a general function? I tried something similar before by replacing inc with f, 3 with n and init with a. So, I am inputting [a n f].
    – sunspots
    Commented Nov 23, 2013 at 3:38
  • @Alex: It sounds like you've got it. What trouble are you having?
    – Chuck
    Commented Nov 23, 2013 at 4:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.