Macros Inject Code

Understand the concept of the quote function in evaluating macros in Elixir.

Introduction

Let’s pretend we’re the Elixir compiler. We read a module’s source top to bottom and generate a representation of the code we find. That representation is a nested Elixir tuple.

If we want to support macros, we need a way to tell the compiler that we’d like to manipulate a part of that tuple. We do that using defmacro, quote, and unquote.

In the same way that def defines a function, defmacro defines a macro. We’ll see what it looks like shortly. However, the interesting part starts not when we define a macro but when we use one.

When we pass parameters to a macro, Elixir doesn’t evaluate them. Instead, it passes them as tuples representing their code. We can examine this behavior using a simple macro definition that prints out its parameter.

Get hands-on with 1200+ tech skills courses.