Monday, April 02, 2007

Said I’m learning Common Lisp. I wanted to learn ‘coz I was told that it’s got super “metaprogramming” powers. I was curious so I decided to take a look myself. They were talking about macros. I am now looking at the macros.

I have not done the macros. There’re more but the bit I have chewed proved judicious. C has macros. Java doesn’t, what a pity, and I think Python and other scripting languages don’t either. Yet C does. However, the macros in C should be ashamed if they still call themselves macros when they have met macros from the Common Lisp language. They’re so different, and the Lisp counterpart is so powerful. It is because it’s dynamic.

The macros in C are just substitutions of small amount of text. It even place limits on the texts to substitute. If you #define M(a, b, c) m_blah_blah(a, b, c), and you try to use the macro M, you have to specify right 3 arguments. What’s more, the resulting code contains just m_blah_blah(a, b, c). There’s no trick to play. The preprocessor is so dumb that it knows nothing about computation or program logic.

While in Lisp, things are so different. A macro is more like a function that returns the text used to substitute the macro text. Well… not so much of texts, but rather, lists. A list is more higher level than just texts ‘coz it got more structural and program logic. When expanding the macros, the compiler actually computes things needed in the expansion. If anything can be calculated from the source code directly rather than human user intervention, the compiler can calculate it and put it right into the generated program, speeding up the runs of it. You don’t need to write another program to pre-generate the source code, and then use the source code to generate a compiled program. Sometimes, generated source is needed, I guess, even by Lisp programs. But not so much as by the C programs. I come to believe that the language is an elegant one. I come to love it.

No comments: