English 中文(简体)
Clojure - Macros
  • 时间:2024-11-03

Clojure - Macros


Previous Page Next Page  

In any language, Macros are used to generate inpne code. Clojure is no exception and provides simple macro facipties 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 pst 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 inpne 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 inpne 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]
      (pst 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 pst.

Output

The above program produces the following output.

(2 2)
Advertisements