Appearance
Optional syntax sheet
Read first: Keyword lists and maps
Source: Elixir guide, Optional syntax sheet.
Elixir lets you omit a few delimiters. Four rules explain all of them, and they keep the core of the language small.
Start with this code:
elixir
if variable? do
Call.this()
else
Call.that()
endNow remove the conveniences, one at a time:
4 steps
do-endblocks are keywords:if variable?, do: Call.this(), else: Call.that()- A Keyword listA list of tuples with two elements, where the first element, the key, is an atom. The keys keep the order that you gave and can repeat. People mostly use them for optional arguments to functions.Read the page · Glossary as the last argument does not need square brackets.
- A keyword list is a list of two-element TupleA fixed collection with curly brackets that can hold any value. Its elements are stored one after the other in memory, so it is fast to read one element by index or to get the size.Read the page · Glossary:
[{:do, …}, {:else, …}] - Parentheses are optional in function calls.
Why it matters
if, def, and defmodule are not special keywords with their own grammar. They are ordinary calls that these four rules build. So this code:
elixir
defmodule Math do
def add(a, b) do
a + b
end
endis the same as this code:
elixir
defmodule(Math, [
{:do, def(add(a, b), [{:do, a + b}])}
])For this reason, you can extend the language with the same constructs that build it (see meta-programming).
You do not need to apply these rules by hand. mix format does it. Unless you configure it otherwise, it always adds parentheses to calls.