Clojure - Macros


Advertisements

In any language, Macros are used to generate inline code. Clojure is no exception and provides simple macro facilities for developers. Macros are used to write code-generation routines, which provide the developer a powerful way to tailor the language to the needs of the developer.

Following are the methods available for Macros.

defmacro

This function is used to define your macro. The macro will have a macro name, a parameter list and the body of the macro.

Syntax

Following is the syntax.

(defmacro name [params*] body)

Parameters − ‘name’ is the name of the macro. ‘params’ are the parameters assigned to the macro. ‘body’ is the body of the macro.

Return Value − None.

Example

An example on how this is used is shown in the following program.

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (defmacro Simple []
      (println "Hello"))
   (macroexpand '(Simple)))
(Example)

Output

The above program produces the following output.

Hello

From the above program you can see that the macro ‘Simple’ is expanded inline to ‘println’ “Hello”. Macros are similar to functions, with the only difference that the arguments to a form are evaluated in the case of macros.

macro-expand

This is used to expand a macro and place the code inline in the program.

Syntax

Following is the syntax.

(macroexpand macroname)

Parameters − ‘macroname’ is the name of the macro which needs to be expanded.

Return Value − The expanded macro.

Example

An example on how this is used is shown in the following program.

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (defmacro Simple []
      (println "Hello"))
   (macroexpand '(Simple)))
(Example)

Output

The above program produces the following output.

Hello

Macro with Arguments

Macros can also be used to take in arguments. The macro can take in any number of arguments. Following example showcases how arguments can be used.

Example

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (defmacro Simple [arg]
      (list 2 arg))
   (println (macroexpand '(Simple 2))))
(Example)

The above example places an argument in the Simple macro and then uses the argument to add argument value to a list.

Output

The above program produces the following output.

(2 2)
Advertisements