使用Enum迭代elixir中的元组列表

问题描述 投票:0回答:2

我试图通过Enum.map迭代元组列表。

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

此代码无效。我怎样才能做到这一点 ?

list tuples elixir enumeration
2个回答
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}]

2
投票

你也可以使用comprehensions

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

理解是枚举的语法糖,所以它相当于使用Enum

© www.soinside.com 2019 - 2024. All rights reserved.