0

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 ?

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
Arun Dhyani
  • 89
  • 1
  • 3

2 Answers2

4

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}]
Dogbert
  • 212,659
  • 41
  • 396
  • 397
3

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.

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
  • FWIW, comprehensions are **not** a syntactic sugar, they are [transpiled into beams on their own](https://github.com/elixir-lang/elixir/blob/9d105ba4d655ecec00b10d35336a15c6b6d9922e/lib/elixir/src/elixir_erl_for.erl#L297-L300). Filters and multiple clauses in comprehensions are _not achievable_ with plain enumeration. – Aleksei Matiushkin Aug 29 '18 at 04:20
  • Interesting, thanks. Although the official guide I linked to says they are syntactic sugar: "In Elixir, it is common to loop over an Enumerable, often filtering out some results and mapping values into another list. Comprehensions are syntactic sugar for such constructs: they group those common tasks into the for special form" – Adam Millerchip Aug 29 '18 at 04:36
  • “such constructs” ≠ “enumerations” :) – Aleksei Matiushkin Aug 29 '18 at 04:37
  • About writing multiple clauses without the special form, I asked a question about that here: https://stackoverflow.com/questions/50653654/elixir-what-does-a-multiple-generator-list-comprehension-look-like-without-the – Adam Millerchip Aug 29 '18 at 04:39
  • It’s possible only unless you have filters/guards in the comprehension. – Aleksei Matiushkin Aug 29 '18 at 04:42