Using Bindings to Inject Values

Remember that there are two ways of injecting values into quoted blocks. One is unquote. The other is to use a binding. However, the two have different uses and different semantics.

A binding is simply a keyword list of variable names and their values. When we pass a binding to quote, the variables are set inside the body of that quote.

This is useful because macros are executed at compile time. This means they don’t have access to values that are calculated at runtime.

Here’s an example. The intent is to have a macro that defines a function that returns its own name:

 defmacro​ mydef(name) ​do
 quote​ ​do
 def​ ​unquote​(name)(), ​do​: ​unquote​(name)
 end
 end

We try this out using something like ...

Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.