I just finished “Programming Elixir” and now I am reading “Metaprogramming Elixir”. I can’t say I comprehend everything. I try to understand but I mostly pretend I understand and keep reading. While the previous examples were somehow manageable to follow I am stuck in recreating the if macro. Here is the code.
defmodule ControlFlow do
defmacro my_if(expr, do: if_block) do
if(expr, do: if_block, else: nil)
end
defmacro my_if(expr, do: if_block, else: else_block) do
quote do
case unquote(expr) do
result when result in [false, nil] -> unquote(else_block)
_ -> unquote(if_block)
end
end
end
end
Can someone please be patient and explain with simple words what is happening in this code?
I understand what quote and unquote do. I don’t understand why the two defmacro definitions.
Now that I write the question I realize the first defmacro is just for the case we have a simple if without else. The second defmacro handles the if/else case. But still I can’t understand how they work.