Home > Articles > Programming

  • Print
  • + Share This
From the author of

Closures and Metaprogramming

Closure is a buzzword in a lot of modern languages, but closures have been in Lisp for a very long time. Because they're simple to create, they're used all over the place in Lisp programs. Even some of the syntax is inherited by other languages. Lisp uses the lambda keyword to define closures—a little bit of syntax picked up by Python, among others. Closures, functions, and macros in Lisp are all defined in almost the same way.

Macros and higher-order functions are very common in Lisp programs. It's been claimed that the correct way to write a program in Lisp is to describe the problem in a domain-specific language and then write an interpreter for that language.

Part of the reason that metaprogramming in Lisp is so common is the homogeneous syntax. In Lisp, programs are represented in S-expressions, which are lists of lists and atoms—the primitive types that Lisp is designed for processing.

Lisp macros are programs that take a set of S-expressions (the program) and produce another set. Other languages have attempted to produce similar metaprogramming tools, such as the C preprocessor and C++ templates, but they're far less flexible. Lisp macros can perform any arbitrary transform on the source code, and they're inherently easy to write because the source code for a Lisp program is written in a form that's trivial to parse.

Detractors claim that LISP stands for "Lots of Irritating and Superfluous Parentheses," and when looking at some Lisp code it's easy to see why. A Lisp expression is either an atom or a list of atoms in brackets ([ ]). For example, (+ 12 x) is an expression that adds 12 to the variable x. The first element in the list tells the Lisp interpreter what to do with the rest of the list. To define a function, you'd begin the list with defun, followed by a list of the arguments, and then followed by the expressions that make up the function body.

The extensive metaprogramming capabilities of Lisp lead to very concise source code. It's possible, for instance, to implement almost all of the design patterns in the Gang of Four book in terms of Lisp macros. Rather than implementing the pattern each time you use it, you just invoke the correct macro and get it for free.

  • + Share This
  • 🔖 Save To Your Account