Exploring Elixir, I tried this:
And it worked. Well, in a sense. The code runs, but it outputs both “true” and “false”.
What’s going on here? Let’s try another experiment:
The keyword list is evaluated before it’s even passed to the function, like any keyword list would be. That includes evaluating the
IO.puts function calls.
Now that we have the full list of block keywords (from the Elixir source) we can go completely crazy:
So these are all available to your own functions, like in our
Example.foobar example. But what use are they if every branch is evaluated all the time?
Macros to the rescue.
Elixir macros get access to the syntax tree of a piece of code, without the code being evaluated first. They can then slice and dice the code and return another syntax tree, that will be evaluated.
if/do/else is just a macro using these keyword lists.
Just for fun, we could make a macro that randomly executes one of two branches, and then always runs the
I haven’t used this myself, other than in silly experiments. I can picture it being handy for some DSLs, though. If you apply this to anything interesting, please do let me know in a comment!