Metaprogramming Elixir – Part One

This is a work through an discussion of Metaprogramming Elixir.

The entry point of metaprogramming in Elixir is the quite macro.

quote do: 1 + 2
{:+, [context: Elixir, import: Kernel], [1, 2]}

This allows the transformation of a code block into the abstract syntax tree (AST). This can then be manipulated like any other data structure and return to the generated code. The practical upshot of this is that half of the Elixir language is actually macros. You can if you need to write your own macros to perform complex operations simply.

There are recommendations to limit the use of macros to things that you can’t solve with normal functions. It’s possible with macros to create a powerful equivalent of inheritance, but must be used sparingly to avoid magical code.

Most of this work takes place at compile time rather than at runtime.

You use require to import macros.

General warning: in languages that have implicit returns adding logging at the end of a function masks the result. Capture the result, log then return result.

unquote is a technique where a macro can read variables from the hosts context. This is how you pass parameters into a macro.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s