DaveIdito
DaveIdito

Reputation: 1606

Use of colon in do expressions in Elixir

I am learning Elixir and I can't seem to understand the usage of :. Following three lines illustrate this:

iex(1)> quote do: 1 + 3
{:+, [context: Elixir, import: Kernel], [1, 3]}

# no `:` but now I need `end`
iex(2)> quote do 1 + 3  end
{:+, [context: Elixir, import: Kernel], [1, 3]}

# Oops! an error
iex(3)> quote do: 1+ 2 end
** (SyntaxError) iex:10:16: unexpected reserved word: end

What does : do here? And why do I get a sytanx error if I use end with : as in third input above?

There is a question about atoms and colon in Elixir here, but it doesn't answer my question (at least to me).

Upvotes: 1

Views: 315

Answers (1)

David Maze
David Maze

Reputation: 158908

do-end blocks have special syntax. The example from the syntax reference (slightly abbreviated) shows that

if true do
  this
end

gets converted to

if(true, do: (this))

In turn, the trailing do: (this) is the keywords as last arguments syntax; it is ordinary key: expression syntax. So the do: (and else:, if present) keywords would get packed into a keyword list

if(true, [do: (this)])
if(true, [{:do, (this)}])

and from there Kernel.if/2 is a macro.

In your example, the same syntax applies, except that you're calling Kernel.SpecialForms.quote/2.

In short, you either need both a do and an end with no colon, or you need do: and no end, but you can't have do: with a colon and also a trailing end.

Upvotes: 7

Related Questions