Resources
- https://elixir-lang.org/getting-started/meta/quote-and-unquote.html
- https://8thlight.com/insights/lispy-elixir
Quote and Unquote
Quote and unquote are metaprogramming utilities related to notions of homoiconicity and Abstract Syntax Trees.
The article I read that gave me my first aha moment for these utilities is Lispy Elixir by Patrick Gombert.
quote
as a reserved word shows up in Lisp, Clojure, and Elixir. Patrick Gombert calls it a "Lispism", implying, I presume, that the syntax was lifted directly from Lisp.
Normally, you write Elixir and the code gets executed. But, maybe you want to write code that will itself write code. This is a metaprogramming desire.
Elixir, under the hood, represents code as a three-tuple.
The first element is the function name, the second is a keyword list containing metadata and the third is the arguments list.
These tuples are essentially abstract syntax trees, though perhaps Elixir doesn't like that term for some reason?
Many languages would call such representations an Abstract Syntax Tree (AST). Elixir calls them quoted expressions
unquote
feels a lot like the code-injection syntax of template strings. For example, in javascript, if you want to inject the value of a variable in a string, you'd write
`the number is ${number}`;
That is approximately what unquote
is doing: evaluating the expression within the quote
d content.
iex> quote do: 1 + 1
{:+, [context: Elixir, imports: [{1, Kernel}, {2, Kernel}]], [1, 1]}
iex> quote do: unquote(1 + 1)
2