Adding dynamic behavior to quotes
As you might guess, it’s not feasible to merge two quoted literals manually every time we need to add dynamic behavior to one. So, Elixir provides other constructs that allow us to manipulate a quoted literal. We’re going to closely look at two of those next – unquote
and var!
.
In Elixir, unquote
is a way to add behavior to a quoted literal at the time of its definition. For example, the following code uses unquote
inside a quoted literal:
iex shell iex> b = 3 iex> quoted_expr = quote do: 1 + unquote(b) {:+, [context: Elixir, import: Kernel], [1, 3]}
As you can see, instead of returning [1, b]
as the third element of the tuple, unquote
evaluates the value of b
to return [1, 3]
as the third element. Therefore, unquote
updates a quoted literal at the time of its definition.
We can use var!
to add behavior to a quoted literal at the time of its evaluation.
Now, consider the following code:
iex shell iex>...