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
:
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
Here's a slightly different solution:
def transpose(m) where length(m) <2, do: m
def transpose(m) do
for i <- 0..length(m)-1 do
Enum.reduce(m,[], fn x,acc -> acc ++ [Enum.at(x,i)] end)
end
end
where m
is your matrix.
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