Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a transpose function in Elixir?

Tags:

elixir

Hi I look for a transpose function in Elixir. For example I have this kind of array a and after calling a function the result should be b:

a = [[1, 2], [3, 4], [5, 6]]
b = transpose(a)
b => [[1, 3, 5], [2, 4, 6]]
like image 680
Furi Avatar asked May 16 '14 21:05

Furi


3 Answers

There (still) isn't one in Elixir, but you can use:

def transpose(rows) do
  rows
  |> List.zip
  |> Enum.map(&Tuple.to_list/1)
end
like image 115
Ivan Kozik Avatar answered Nov 12 '22 00:11

Ivan Kozik


There isn't one in Elixir currently, but you could create your own with:

def transpose([]), do: []
def transpose([[]|_]), do: []
def transpose(a) do
  [Enum.map(a, &hd/1) | transpose(Enum.map(a, &tl/1))]
end
like image 13
bitwalker Avatar answered Nov 12 '22 01:11

bitwalker


Since Elixir v1.12, you can use the following to transpose a two-dimensional list:

Enum.zip_with(list, & &1)
like image 6
Oskar Avatar answered Nov 11 '22 23:11

Oskar