O'Reilly logo

Learning Elixir by Kenny Ballou

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

Our first macros

Now that we have the basics of abstract syntax trees, let's dive into macros, the heart of metaprogramming.

Macros, in the context of Elixir, are a means of deferring the evaluation of certain code. That is, instead immediately expanding an expression, say, when a value is passed, the expression will be passed in its quoted form to the macro. The macro would then be able to decide what it should do with the expressions passed.

This may become more clear when comparing macros to functions. For example, let's attempt to (re)create the if-else construct using a function:

defmodule MyIf do def if(condition, clauses) do do_clause = Keyword.get(clauses, :do, nil) else_clause = Keyword.get(clauses, :else, nil) case condition do val when ...

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