[英]Iterating over list of tuples in elixir using Enum
I am trying to iterate over a list of tuples through Enum.map . 我试图通过Enum.map遍历元组列表。
coordinates = [{0,0},{1,0},{0,1}]
newcoordinates = Enum.map(coordinates,fn({X,Y})->{X+1,Y+1})
This code is not valid . 此代码无效。 How can I do this ? 我怎样才能做到这一点 ?
First of all, you're missing an end
after the function declaration. 首先,在函数声明之后您缺少end
。 Second, in Elixir, identifiers starting with upper case are atoms and lower case are variables, unlike Erlang where upper case are variables and lower case are atoms. 其次,在Elixir中,以大写字母开头的标识符是原子,而小写字母是变量,而Erlang不像大写字母是变量,小写字母是原子。 So you just need to make them lowercase: 因此,您只需要使它们小写即可:
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}]
You can also use comprehensions : 您还可以使用comprehensions :
for {x, y} <- [{0,0},{1,0},{0,1}], do: {x+1, y+1}
Comprehensions are syntactic sugar for enumeration, so it's equivalent to using Enum
. 理解是枚举的语法糖,所以等效于使用Enum
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.