mattfara50
Is the default operator a macro?
This states that the compiler creates new functions given the default operator. Is this actually a macro?
Marked As Solved
Eiji
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 defor 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<-- seeforandwith\\- 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}
Also Liked
al2o3cr
\\ 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:
Last Post!
mattfara50
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









