In Elixir, why can't I use different notations when creating a map?

There are two different syntax for defining a map:

map = %{:a => 1, :b => 2} #=> %{a: 1, b: 2} map = %{a: 1, b: 2} #=> %{a: 1, b: '2} 

Using both methods when defining a map, do the following:

 map = %{:a => 1, b: 2} #=> %{a: 1, b: 2} 

But used in a different order causes an error:

 map = %{a: 1, :b => 2} #=> ** (SyntaxError) iex:37: syntax error before: b 

Why?

EDIT

OS: Ubuntu 15.4

Elixir: 1.1.1

+6
source share
2 answers

Like my problem on Github (which I really shouldn't have opened), this is not a mistake.

The first answer (which I really did not understand):

This is not a mistake, it is the same syntactic sugar that is used for keywords on the last argument of the function.

 foo(bar, baz: 0, boz: 1) #=> foo(bar, [baz: 0, boz: 1]) 

The map syntax is presented as a function call in AST:

 iex(1)> quote do: foo(bar, baz: 0, boz: 1) {:foo, [], [{:bar, [], Elixir}, [baz: 0, boz: 1]]} iex(2)> quote do: %{baz: 0, boz: 1} {:%{}, [], [baz: 0, boz: 1]} 

So why the keyword syntax for maps only works for the last (or only) argument.

And the second answer, which sounded Ok in a sense, is that I think I got it:

The simple answer is: b: 2 is the syntactic sugar for [b: 2] , but only sugar works when it is at the end of a function or “construct” call, for example %{} .

+3
source

Maybe for the sake of consistency? It is like walking with a trigger and a boot. You may look strange, but still extremely uncomfortable.

0
source

All Articles