2015-11-19 39 views
6

有2個不同定義的映射的語法:在Elixir中,爲什麼創建地圖時不能使用不同的符號?

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

同時使用而定義的映射的工作原理如下:

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

但在其他順序使用引發錯誤:

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

爲什麼?

編輯

操作系統:Ubuntu的15.4

藥劑:1.1.1

+2

這可能是一個在Elixir中的錯誤。 –

+0

你可能想添加一些細節。 Elixir,OS等版本 –

回答

3

根據my issue on Github(我其實不應該打開),這不是一個錯誤。

第一個答案(我並沒有真正得到):

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.

而第二個答案,這在一定意義上,我認爲我得到了它聽起來好:

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

也許出於一致性的緣故?這就像一個觸發器和一個哥特靴子走。你可能看起來很花哨,但仍然非常不方便。

相關問題