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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With