Macros Quick Review 

Typically, when we call a procedure we follow three steps:

  1. Evaluate the operator

  2. Evaluate the operands

  3. Apply the operator to the operands

However, with macros, we do the same steps, but in a slightly different order:

  1. Evaluate the operator

  2. Apply the operator to the operands

  3. Evaluate the operands

But wait, how could we apply a procedure when we don’t even know what we’re applying it to? Believe it or not, you actually can. When we write a macro, the goal is to fill in our macro’s operands into some sort of list. Why a list? Well, we know that when we run a macro, we apply our procedure and then evaluate our operands. We also know that any functional line of code in scheme is structured as a list. So, if we create a list that when evaluated, runs the operation that we want our macro to, then evaluate it, we’ll be running the operation we want our macro to run.

How To write a macro

Writing a macro sounds harder than it is; in fact, you can break it down into two steps, both of which you already learned how to do earlier in the scheme unit.

  1. Write out the expression that you want the macro to evaluate when it is run

  2. Construct the list that will create that expression

Basically, all you have to do is write out an expression in scheme, and then create a list. Nice!

LET’S SEE IT ON AN EXAMPLE

Let me actually show this macro-writing process on an example, since it still might seem a little unclear.

Let’s create a macro that represents an if statement, and takes in a condition, a true result, and a false result.

(define (if-macro cond true-res false-res)

Okay, so the first step is to write out the expression that we want the macro to evaluate when it is run. We know that we want the body of our macro to evaluate an if statement, so we probably want an if statement, which we already know how to write from the scheme unit.

(if cond true-res false-res)

Cool, got the first step down. Now let’s construct a list that will return that expression. If we look at the above expression, it looks like it’s just a list of four elements, if, cond, true-res, and false-res. Do we know how to make a list of four elements? Yes, we’ve already learned that too!

(list ‘if cond true-res false-res)

Believe it or not, the above line is actually the body of our macro. So our final answer should look like this:

(define (if-macro cond true-res false-res) (list ‘if cond true-res false-res))

We can check this by running our macro on a very simple example:

(if-macro 0 1 2)

Our macro will construct the list:

(if 0 1 2)

which when evaluated will give us 1, just like we want.