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 val in [false, nil] -> else_clause _ -> do_clause end end end
After loading into iex
, using MyIf
may look something similar to the following lines of code:
iex(1)> c "myif.exs" [MyIf] iex(2)> MyIf...