从列表创建结构

时间:2018-04-29 21:56:03

标签: elixir

我的模块中有以下结构列表:

defmodule Team do
  defstruct name: nil, points: nil
end

team1 = %Team{name: "Team 1", points: "00"}
team2 = %Team{name: "Team 2", points: "50"}
team3 = %Team{name: "Team 3", points: "25"}
team4 = %Team{name: "Team 4", points: "12"}
team5 = %Team{name: "Team 5", points: "04"}
team6 = %Team{name: "Team 6", points: "32"}

teams = [team1, team2, team3, team4, team5, team6]

我也有以下结构:

defmodule Match do
  defstruct team1: nil, team2: nil
end

如何基于此列表中的团队组合匹配列表?

例如,匹配:team1,team2

2 个答案:

答案 0 :(得分:3)

@Hauleth已经使用递归发布了正确的答案,但我会使用Enum.chunk_every/2来简化:

for [a, b] <- Enum.chunk_every(teams, 2), do: %Match{team1: a, team2: b}

答案 1 :(得分:2)

是的,你可以很容易地做到这一点:

def build(list), do: do_build(list, [])

defp do_build([], result), do: result
defp do_build([a, b | rest], result), do: do_build(rest, [%Match{team1: a, team2: b} | result])
defp do_build(_, _), do: raise "Odd number of elements in list"