Is there a transpose function in Elixir?

为君一笑 提交于 2020-01-02 01:30:29

问题


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]]

回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/23705074/is-there-a-transpose-function-in-elixir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!