2015-11-19 7 views
6

Ci sono 2 diverse sintassi di definizione di una mappa:In elisir perché non posso usare notazioni diverse durante la creazione di una mappa?

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

Utilizzando sia come segue durante la definizione di una mappa funziona:

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

Ma utilizzato in altro ordine genera un errore:

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

Perché?

EDIT

OS: Ubuntu 15.4

Elixir: 1.1.1

+2

Questo può essere un bug in Elisir. –

+0

Si consiglia di aggiungere alcuni dettagli. Versione di elisir, sistema operativo ecc. –

risposta

3

Come da my issue on Github (che in realtà non avrei dovuto aprire), questo non è un bug.

Prima risposta (che non ho davvero capito):

It's not a bug, it's the same syntax sugar that is used for keywords on the last argument of a function.

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

The map syntax is represented as function call in the 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]} 

That's why the map keyword syntax only works for the last (or only) argument.

E la seconda risposta, che suonava male in un senso che penso ho preso:

Simple answer: b: 2 is syntax sugar for [b: 2] , but the sugar only works when it is at the end of a function call or "construct" such as %{} .

0

Forse per motivi di coerenza? È come camminare con una flip-flop e uno stivale goth. Puoi sembrare stravagante, è ancora estremamente scomodo.

Problemi correlati