Hy and macros

Couple last evenings I have been working on macros and spend my time trying to wrap my head around them. Unlike in some other languages, macros in Lisp are actually executable code and can be used to generate more code. Macros are handled in macro expansion time. During this time the macros are executed and the code they generate is placed in the program. After the macro expansion the program can start running.

I wrote a very simple macro, that is not really even useful, other than to try out things:

(defmacro counter [x &optional y] (if y (quasiquote (+ (unquote x) (unquote y))) x))

The macro takes one or two parameters. If one parameter is given, the macro does not do anything. With two parameters, it calculates their sum.

If the macro is called with a single parameter like:

(counter 5)

the generated program code will be simply:

5

However, if the macro is called with two parameters:

(counter 5 5)

the generated program will be:

10

x and y don’t have to be simple values, they can be function calls:

(counter (+ 2 2) (- 6 4))

which results:

6

How does the macro work then?

(defmacro counter [x &optional y] (if y (quasiquote (+ (unquote x) (unquote y))) x))

When the macro is executed, first it checks is the y defined. If it is not defined, the x is returned and macro finishes. This causes the first parameter to be placed in the program code as it is.

If the y is defined, the macro starts generating code. Quasiquote is used to mark that the code after it should not be executed, but rather returned to the program. Unquote on the other hand makes sure that the value of parameter x is placed there, instead of letter x.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s