Given an Elixir list with single elements, how to best create a list with pairs of adjacent elements? This should work for any list, not just containing numbers.
Input: [1,2,3,4,5,6,7]
Output: [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
The following solution works, but it looks clumsy to me.
Is there a better / simpler way to do this?
> {[_|list],_} = Enum.map_reduce([1, 2, 3, 4, 5, 6, 7], nil, fn(x, acc) -> {[acc,x], x} end)
{[[nil, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]], 7}
> list
[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]
Just out of curiosity:
with [_|rotated] = list <- [1,2,3,4,5,6,7],
do: list |> Enum.zip(rotated) |> Enum.map(&Tuple.to_list/1)
#⇒ [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]
NB I am posting this as another answer, since in general it’s worse than the accepted one, but it shows the very different approach, that might be taken when there is no ready-to-use Enum function out of the box existing.
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