O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required