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]
One way to do it is by concat
ting nil
before and after the collection and partition
ing 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With