Iterating through a list in pairs
Sometimes, it is useful to be able to take a list of things, and traverse it in pairs.
For an example, if you had the list [1, 2, 3, 4]
, traversing it in pairs would result in the first iteration getting [1, 2]
, then [2, 3]
, and finally[3, 4]
.
One use case for traversing a list this way is to find the deltas between each pair of items in a list. Another is to check if a given list has already been sorted.
Listed below are ways to implement this in a few different languages:
Ruby
> (1..4).each_cons(2) { |a, b| p [a, b] }[1, 2]
[2, 3]
[3, 4]
=> nil
Elixir
iex(1)> [1, 2, 3, 4] |> Enum.chunk_every(2, 1, :discard)[[1, 2], [2, 3], [3, 4]]
Python
>>> items = [1, 2, 3, 4]
for a, b in zip(items, items[1:]):
print [a, b][1, 2]
[2, 3]
[3, 4]
Javascript
> const R = require('ramda')
> R.aperture(2, [1, 2, 3, 4])[[1, 2], [2, 3], [3, 4]]
Note: The above example requires the https://ramdajs.com/ library.