使用Enum遍历Elixir中的元组列表

时间:2018-08-28 18:36:07

标签: list tuples elixir enumeration

我试图通过Enum.map遍历元组列表。

coordinates = [{0,0},{1,0},{0,1}]
newcoordinates = Enum.map(coordinates,fn({X,Y})->{X+1,Y+1})

此代码无效。我该怎么办?

2 个答案:

答案 0 :(得分:3)

首先,在函数声明后缺少end。其次,在Elixir中,以大写字母开头的标识符是原子,而小写字母是变量,而Erlang不像大写字母是变量,小写字母是原子。因此,您只需要使它们小写即可:

iex(1)> coordinates = [{0, 0},{1, 0},{0, 1}]
[{0, 0}, {1, 0}, {0, 1}]
iex(2)> newcoordinates = Enum.map(coordinates, fn {x, y} -> {x + 1, y + 1} end)
[{1, 1}, {2, 1}, {1, 2}]

答案 1 :(得分:1)

您也可以使用comprehensions

for {x, y} <- [{0,0},{1,0},{0,1}], do: {x+1, y+1}

理解是枚举的语法糖,因此等效于使用Enum