在任何语言中,宏都用于生成内联代码, Clojure也不异常,它为开发人员提供了简单的宏函数。

defmacro 定义宏

此函数用于定义您的宏,宏将具有宏名称,参数列表和宏的主体。

(defmacro name [params*] body)

参数      -  "name"是宏的名称, "params"是分配给宏的参数, " body"是宏的主体。

返回值  -  无。

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

上面的程序产生以下输出。

Hello

从上面的程序中,您可以看到宏" Simple"被内联扩展为" println"" Hello",宏与函数相似,唯一的区别是在使用宏的情况下,将判断表单的参数。

macro-expand 扩展宏

这用于扩展宏并将代码内联到程序中。

(macroexpand macroname)

参数    -   "macroname"是需要扩展的宏的名称。

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

上面的程序产生以下输出。

Hello

带参数的宏

宏也可以用来接受参数,宏可以接受任意数量的参数,以下示例展示了如何使用参数。

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

上面的示例将一个参数放在Simple宏中,然后使用该参数将参数值添加到列表中。

上面的程序产生以下输出。

(2 2)

参考链接

https://www.learnfk.com/clojure/clojure-macros.html