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.

sunspots
  • 1,047
  • 13
  • 29

1 Answers1

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))
Chuck
  • 234,037
  • 30
  • 302
  • 389
  • 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 Nov 23 '13 at 03:38
  • @Alex: It sounds like you've got it. What trouble are you having? – Chuck Nov 23 '13 at 04:38