On p. 6, there is this example:
defmodule Math do
# {:+, [context: Elixir, import: Kernel], [5, 2]}
defmacro say({:+, _, [lhs, rhs]}) do #line 4
quote do
lhs = unquote(lhs)
rhs = unquote(rhs)
result = lhs + rhs
IO.puts "#{lhs} plus #{rhs} is #{result}"
result
end
end
# {:*, [context: Elixir, import: Kernel], [8, 3]}
defmacro say({:*, _, [lhs, rhs]}) do #line 15
quote do
lhs = unquote(lhs)
rhs = unquote(rhs)
result = lhs * rhs
IO.puts "#{lhs} times #{rhs} is #{result}"
result
end
end
end
The text says:
Let’s break down the code. Since we know macros receive the AST representation of the arguments we pass to them, we pattern matched directly on the AST to determine which
say
definition to invoke. On lines 4 and 15, we can see that macros , like functions, can have multiple signatures. Having the example representation from our quoted results allowed us to easily bind the left- and right-hand side values to variables and print a message accordingly. Too complete the macro, we usedquote
to return an AST for the caller to replace our Math.say invocations. Here we also used unquote for the first time…
What in the world does:
Having the example representation from our quoted results allowed us to easily bind the left- and right-hand side values to variables and print a message accordingly.
mean?! I recognize the words as English, but they have no intelligible meaning to me.