Metaprogramming Elixir book: what does this mean?

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 used quote 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.

1 Like

Ahh, I figured it out. The phrase “Having the example representation from our quoted results” refers to:

 # {:+, [context: Elixir, import: Kernel], [5, 2]}

The “quoted results” are on the previous page where the book used quote() on some math expressions.

4 Likes

That is my understanding as well. Just for some confirmation.

If you’re looking at the commented out representation of the AST and then imagine how that will be matched against the function head, it’s easy to see how 5 and 2 will be bound to the right-hand and left-hand variables.

2 Likes

can confirm :slight_smile:

4 Likes

lol. Thanks!

I would, however, suggest a rewrite. I read that sentence 20 times, and I couldn’t figure out what it meant until just after I posted my question (as sometimes happens!). Maybe something as simple as:

With the AST in the comments as a guide we were easily able to bind the left- and right-hand side values to variables and print a message accordingly .

2 Likes