简体   繁体   中英

Iterating over list of tuples in elixir using Enum

I am trying to iterate over a list of tuples through 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. 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. 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 :

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM