Macro is similar to a function in popular languages like C++, java, etc. that takes arguments and returns a LISP form to be evaluated. It is useful when the same code has to be executed with a few variable changes.
For example, rather than writing the same code for squaring a number, we can define a macro that holds the code for squaring.
Defining a Macro:
To define a named macro in LISP, a default macro – defmacro is used.
Syntax:
(defmacro macroName (parameters) expressions )
Where,
- macroName: It is the identifier of the macro, wherever it is used the macro expressions will be executed
- parameters: Parameters that can be passed whenever calling a macro
- expressions: Statements executed wherever the macro is used.
Example
Lisp
(defmacro sayHello () ; This statement will be executed whenever
; we use the macro sayHello
(write - line "Hello everyone" )
) ; Using macro sayHello (sayHello) (write - line "GfG" )
(sayHello) (terpri) (defmacro greet (name) ; This statement will be executed whenever
; we use the macro greet
; substituting name with the parameter value
( format t "Welcome ~S ~%" name)
) ; Calling macro square with parameter strings (greet "GfG audience" )
(greet "Awesome people" )
(terpri) (defmacro sumup (a b) ; This line will be executed whenever
; we use the macro sum
; with two integer parameters
( format t "~D + ~D : ~D" a b ( + a b))
) ; Calling macro sumup with parameters 7 and 18 (sumup 7 18 )
(terpri) (defmacro square (num) ; This line will be executed
; whenever we use the macro square
; with the parameter name
( format t "Square of ~D is ~D " num ( * num num))
) ; Calling macro square with parameter 5
(square 5 )
(terpri) |
Output:
Hello everyone GfG Hello everyone Welcome "GfG audience" Welcome "Awesome people" 7 + 18 : 25 Square of 5 is 25
Article Tags :