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
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))
-
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].– sunspotsCommented Nov 23, 2013 at 3:38
-
@Alex: It sounds like you've got it. What trouble are you having?– ChuckCommented Nov 23, 2013 at 4:38