Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Elixir when do we use the colon before or after the atom name?

Tags:

elixir

I'm busy learning Elixir and understand what is an atom is. On the basic types page they're introduced like this:

:foo

However, when we encounter keyword lists we see atoms like this

list = [{:a, 1}, {:b, 2}]   # list of tuples
list == [a: 1, b: 2]        # evaluates as true

The placing of the colon has been swapped to appear after the name of the atom.

It seems that when an atom is a key then the positioning of the colon changes. This does make the code easier to read because it's quite expressive, but I can't find any direct reference to why this is the case (this isn't the only site that I'm looking at learn Elixir).

Could somebody confirm that I'm right in assuming that atoms have the colon placed on the right when they're the key in a list?

Also to me this just makes the code prettier, but is there actually some deeper understanding that I'm missing as to why this happens?

like image 551
Andy Avatar asked May 07 '16 14:05

Andy


1 Answers

Yes, it's just syntactic sugar for atom keys. It was presumably implemented because atoms are widely used as keys in keyword lists and maps, and the shorter syntax makes them easier to read. As you've already correctly observed, the following proplists are equivalent:

[{:a, 1}, {:b, 2}]
[a:1, b:2]

The following maps are also equivalent:

%{:a => 1, :b => 2}
%{a: 1, b: 2}
like image 71
Patrick Oscity Avatar answered Sep 30 '22 10:09

Patrick Oscity