English 中文(简体)
LISP - Macros
  • 时间:2024-11-05

LISP - Macros


Previous Page Next Page  

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-pst))
"Optional documentation string."
body-form

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

Example

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.psp and type the following code in it.

(defmacro setTo10(num)
(setq num 10)(print num))
(setq x 25)
(print x)
(setTo10 x)

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

25
10
Advertisements