A.25.1 Defining and using macros
Macros are defined for the current module using one of the three constructs below.
#define(Macro, Replacement). #define(Macro, Replacement) :- Code. #import(ModuleFile).
Macro is a callable term, not being define(_,_)
,
or import(_)
.
Replacement is an arbitrary Prolog term. Code is a
Prolog body term that must succeed and can be used to
dynamically generate (parts of) Replacement.
The #import(ModuleFile)
definition makes all macros from
the given module available for expansion in the module it appears.
Normally this shall be appear after local macro definitions.
A macro is called using the term #(Macro)
. #
is defined as a low-priority (10) prefix operator to allow for #Macro
.
Macros can appear at the following places:
- An entire sentence (clause)
- Any argument of a compound. This implies also the head and body of a clause.
- Anywhere in a list, including as the tail of a list
- As a value for a dict key or as a dict key name.
Macros can not appear as name of a compound or tag of a dict.
A term
#Macro
appearing in one of the allowed places must
have a matching macro defined, i.e., #Macro
is always
expanded. An error is emitted if the expansion fails. Macro expansion is
applied recursively and thus, macros may be passed to macro arguments
and macro expansion may use other macros.
Macros are matched to terms using Single Sided Unification
(SSU), implemented using Head => Body
rules. This
implies that the matching never instantiates variables in the term that
is being expanded.
Below are some examples. The first line defines the macro and the indented line after show example usage of the macro.
#define(max_width, 100). W < #max_width #define(calc(Expr), Value) :- Value is Expr. fact(#calc(#max_width*2)). #define(pt(X,Y), point{x:X, y:Y}). reply_json(json{type:polygon, points:[#pt(0,0), #pt(0,5), #pt(5,0)]}).
Macro expansion expands terms #(Callable)
. If the
argument to the
#-term is not a callable
, the #-term is not modified. This
notably allows for #(Var)
as used by library(clpfd)
to indicate that a variable is constraint to be an (clp(fd)
)
integer.