Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: How to create a pair of elements from List

Tags:

elixir

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]]
like image 522
Tilo Avatar asked Nov 26 '25 13:11

Tilo


1 Answers

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.

like image 144
Aleksei Matiushkin Avatar answered Nov 28 '25 16:11

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!