This states that the compiler creates new functions given the default operator. Is this actually a macro?
\\
is parsed as an operator (like +
or ==
or ->
etc) but not normally defined anywhere:
iex(1)> 4 \\ 5
** (CompileError) iex:1: undefined function \\/2 (there is no such import)
iex(1)> quote do
...(1)> 4 \\ 5
...(1)> end
{:\\, [], [4, 5]}
The implementation of def
transforms the AST that’s passed to it with pattern matching, but no function named \\
ever runs:
No, look that you cannot use \\
in function body. Elixir
is capable of parsing a predefined set of operators. Some of them are macros, but some of them are used only within other macros (like def
or defp
) and because of that their AST
representation is used instead.
(…) these operators appear in the precedence table above but are only meaningful within certain constructs:
=>
- see%{}
when
- see Guards<-
- seefor
andwith
\\
- see Default arguments
Take a look at a simplest example:
defmodule Example do
defmacro sample({:\\, _, [left, right]}) do
quote bind_quoted: [left: left, right: right] do
if is_nil(left) do
{:right, right}
else
{:left, left}
end
end
end
end
iex> require Example
Example
iex> Example.sample(1 \\ 2)
{:left, 1}
iex> Example.sample(nil \\ 2)
{:right, 2}
Since \\
is a valid operator you are also able to define it, so it can be used inside function body:
defmodule Example do
def left \\ right do
{left, right}
end
end
iex> import Example
Example
iex> 1 \\ 2
{1, 2}
Thank you. I have a lot to learn.