Search code examples
clojure

How to iterate over a collection and have access to previous, current and next values on each iteration?


How can I iterate the elements of a collection in Clojure so I can access the previous, current and next values in every iteration.

With the following vector:

[1 2 3 4]

I would like to have access to the following values in each iteration:

[nil 1 2]
[1 2 3]
[2 3 4]
[3 4 nil]

Solution

  • One way to do it is by concatting nil before and after the collection and partitioning it by elements of 3 with a step size of 1.

    (def c [1 2 3 4])
    (def your-fn println) ;; to print some output later
    (map your-fn
         (map vec (partition 3 1 (concat [nil] c [nil]))))
    

    (You can remove the map vec part if it is also fine if the elements are a LazySeq instead of a vector.)

    Which prints:

    [nil 1 2]
    [1 2 3]
    [2 3 4]
    [3 4 nil]