Friday, November 05, 2010

Macros and meta-macros

Life is repetition.  We do the same things, day after day.  Within each day at work, we find ourselves performing the same actions, more or less.   The great thing about computers is that tasks performed on computers can be automated.  So any time we find that we are repeated ourselves on the computer, we have an opportunity of creating a tool that will allow us to eliminate repetition.

Macros are a great example of this, and one of the defining feature of lisp.  Sure, c++ has macros as well, and they share same of the same capabilities as lisp's macros, but in general the power of lisp macros make them better for everyday use.  Macros are great tools to reduce repetitive code to simple forms.  Code such as:

Seems reasonable enough if you just are opening up one file.  But what if you do this all the time?  Even the simple boilerplate here starts to add up.  That's why common lisp created a macro of an easy way to do this:

What a breath of fresh air that is... there is absolutely nothing wasted here.  All repetitive and wasted code has been removed, leaving only the essence of the task.  That's the art of the macro.  It's one thing to be able to write macros, but to recognize patterns of repetition is a skill worth practicing.

Meta-macros are a term I just made up for this post, which describes repetitive coding tasks we have to perform.  To take a simple example, perhaps you are always navigating to the same files.  Like macros, it is essential that we realize we are doing something repetitive, and that this task can be removed with automation.  In this case, emacs provides a solution: bookmarks.  Many times the solution isn't provided by emacs, though, or the patterns are more complicated.   Every time I change or add a new function in my .cc file, I have to edit my .h file as well.  This is just a natural part of editing C++ code, something so ingrained in us that it's hard to even imagine not going through the trouble of essentially adding function definitions twice.  It's a plainly repetitive task, which could certainly be automated with a meta-macro, by which I mean some elisp code.

Sometimes these meta-macro's automation can increase complexity.  It works fine 98% of the time, but 2% of the time it screws you up and you stop using the meta-macro in frustration.  But macros can have the same trait.  Good macros are actually a bit hard to write, and can be very confusing when they fail.  Meta-macros can be even worse, due to the complexity of the meta level in which we operate.  It takes dedication to solve each new problem you encounter, making your meta-macro more and more robust.  But, with enough effort, you will have an elegant solution that makes you more productive, and able to focus on problem solving, not mere coding.

When you do, please share it with the word.  We all need the help.