Search code examples
clojureclojure-contrib

Iterating in Clojure over vectors


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.


Solution

  • 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))