Lisp - Macros



Macros allow you to extend the syntax of standard LISP.

Technically, a macro is a function that takes an s-expression as arguments and returns a LISP form, which is then evaluated.

Defining a Macro

In LISP, a named macro is defined using another macro named defmacro. Syntax for defining a macro is −

(defmacro macro-name (parameter-list))
"Optional documentation string."
body-form

The macro definition consists of the name of the macro, a parameter list, an optional documentation string, and a body of Lisp expressions that defines the job to be performed by the macro.

Example - Create Macro

Let us write a simple macro named setTo10, which will take a number and set its value to 10.

Create new source code file named main.lisp and type the following code in it.

main.lisp

; define a macro accepting a number
(defmacro setTo10(num)
; set the num as 10 and print it
(setq num 10)(print num))
; set a variable x as 25
(setq x 25)
; print the variable
(print x)
; call the macro
(setTo10 x)

Output

When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −

25
10

Example - Macro with multiple parameters

Let us write another macro named setValue, which will take two paramters and update them to new value.

Create new source code file named main.lisp and type the following code in it.

main.lisp

; define a new macro accepting three values
(defmacro setValue(num1 num2 value)
(progn
   ; assign value to num1
   (setq num1 value)
   ; assing value to num2
   (setq num2 value))
   ; print num1 and num2
   (print num1)
   (print num2)
)
; define paramters	
(defparameter num1 1)
(defparameter num2 2)

; print the paramters before macroo
(print "Values: ")
(print num1)
(print num2)

; print parameters in macros
(print "Values within macro: ")
(setValue num1 num2 3)

; print parameters after running macro, values will be unaffected
(print "Values after macro: ")
(print num1)
(print num2)

Output

When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −

"Values: "
1
2
"Values within macro: "
3
3
"Values after macro: "
1
2
Advertisements