ch1_6_macros
Macros
Let's see simple example, without explaining the syntax of macro definition:
>(defmacro do3times (a) `(progn ,a ,a ,a nil)) ; special form DEFMACRO defines macro DO3TIMES >(do3times (print "Hello")) ; function PRINT will be called three times "Hello" "Hello" "Hello" NIL
When the first symbol DO3TIMES
is recognized as a name of a macro, the form will be treated as macro-expansion form. In principle it means that two-step evaluation will happen. First the non-evaluated argument (print “Hello”)
is submitted to the procedure we defined by DEFMACRO
that will decide what to do with it - macro can evaluate, reorder, restructure the forms - and will return new piece of code. In the second step, the code is evaled.
The first step is called macro expansion and can be examined with a function MACROEXPAND
>(macroexpand '(do3times (print "Hello"))) ; we expand the previously called command (PROGN (PRINT "Hello") (PRINT "Hello") (PRINT "Hello") NIL) ; this is the returned code T
ch1_6_macros.txt · Last modified: 2025/01/14 09:14 by admin