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
Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
18 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...