Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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]
like image 434
eliocs Avatar asked Dec 11 '22 13:12

eliocs


1 Answers

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]

like image 98
Erwin Rooijakkers Avatar answered May 23 '23 13:05

Erwin Rooijakkers