Evaluating quoted literals
In Elixir, we can quickly evaluate a quoted literal using the Code.eval_quoted/3
function. So, let’s use that function to better understand quoted literals:
iex shell iex> quoted_expr = quote do: 1 + 1 {:+, [context: Elixir, import: Kernel], [1, 1]} iex> Code.eval_quoted(quoted_expr) {2, []}
The preceding quoted literal gets evaluated as expected. You might have noticed that Code.eval_quoted/3
returns a two-element tuple. The first element is the result of the evaluation, and the second element is binding
(variables defined) with which the quoted literal was evaluated. Now, let’s introduce some dynamic behavior to the expression:
iex shell iex> quoted_expr = quote do: 1 + b {:+, [context: Elixir, import: Kernel], [1, {:b, [], Elixir}]} iex> Code.eval_quoted(quoted_expr) ** (CompileError) nofile:1: undefined function b/0
The preceding code shows us a variable to the quoted literal. The variable needs to be defined during...