🎓 A1Learner
🔍
0 of 46 lessons completed

Elixir Quote and Unquote

Quote turns Elixir code into data that a program can read and build. Unquote puts a value from outside into that data.

Quote turns code into data

Quote holds 1 + 2 as data instead of adding it.

ast = quote do: 1 + 2
IO.puts(is_tuple(ast))
IO.puts(elem(ast, 0))

Unquote inserts a value

The value of price is placed into the quoted sum before it runs.

price = 10
quoted = quote do: unquote(price) + 5
{result, _binding} = Code.eval_quoted(quoted)
IO.puts(result)

Quoted code is an ordinary tuple

The parts of 1 + 2 can be counted like any other list.

ast = quote do: 1 + 2
parts = elem(ast, 2)
IO.puts(length(parts))
IO.puts(hd(parts))

Example

name = "Ana"
price = 20
quoted_message = quote do: "Hello, " <> unquote(name)
{message, _binding} = Code.eval_quoted(quoted_message)
quoted_total = quote do: unquote(price) + 5
{total, _other} = Code.eval_quoted(quoted_total)
IO.puts(message)
IO.puts(total)

Key points

  • Quote: quote turns a code expression into data.
  • Unquote: unquote inserts a value into quoted code.
  • AST: quoted code is stored as ordinary tuples.
  • Use Code.eval_quoted to run quoted code and get its result.
  • Use elem to read one part of a quoted tuple.

In this example, quote builds a greeting from the name and a sum from the price, then Code.eval_quoted runs each quoted piece and the results are printed.

Note

quoted code does not run when it is built.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does quote do: 1 + 2 return?