Previous Home Contents Next

Chapter 12: Source macros

12.1 Macro definition

12.2 Macro expansion

12.3 Examples

12.4 Points of style

12.1 : Macro definition

Aldor provides a way to define abbreviations, or macros, to make programs easier to read.

A common use of macros is to abbreviate names or type expressions, as in the example below. The lines containing "==>" are macro definitions:

The left hand side of a macro definition may be either an identifier or an application. A definition of the form

Op Parms ==> Body

is equivalent to

Op ==> macro Parms +-> Body

and defines a parameterized macro. Any application syntax is permitted on the original left hand side: prefix, infix, or bracketed. The resulting right hand side is called a macro function.

This rule is applied until the left hand side is an identifier. Macros may consequently be defined to receive their arguments in groups, in a ``curried'' fashion. For example, when P1 and P2 are parameter sequences, the definition

Op (P1)(P2) ==> Body

is equivalent to

Op ==> macro (P1) +-> macro (P2) +-> Body

Macro functions may appear directly in the source program, and may be written with their parameters in groups:

macro (P1)(P2)...(Pn) +-> Body

is equivalent to

macro (P1) +-> macro (P2) +-> ... macro (Pn) +-> Body

12.2 : Macro expansion

The process or replacing the abbrevations with what they stand for is called macro expansion. Macro expansion works by making substitutions in the parsed form of programs. Because the substitution is on trees, it is not necessary to include extra parentheses in macro definitions.

Macro expansion transforms the source syntax trees with the following steps:

Once macro expansion is complete, the entire program should be free of macro definitions and macro functions. The process of macro expansion removes all macro definitions; any remaining unreduced macro functions are reported as errors.

12.3 : Examples

Given the following definitions,

the following expressions expand as shown:

12.4 : Points of style

It is often convenient to use macros which are local to a function or expression. Below, we show a macro "l1?" which is local to the function "f".

The purpose of "l1?" is to provide an inexpensive test whether a list has length one. This example illustrates two additional points:

If the body of the macro is large, having a "where" at the end of a long expression can make a program harder to read. A convenient way to introduce local variables in this case is to make the left-hand side of the "where" a local macro.

Just as a macro function

is analogous to a function "Parms +-> Body", a macro definition

is analogous to a definition "Lhs == Expr". For this reason, a macro definition may be written in the equivalent form

Previous Home Contents Next