宏:defmacro / macroexpand

过程式宏、准引用模板、syntax-rules 卫生宏,以及展开过程的查看。

(defmacro unless [test body]
  (list 'if test nil body))
(unless false :ran)

准引用让宏可读。

(defmacro my-when [test & body]
  `(if ,test (do ,@body) nil))
(my-when true 1 2 3)

syntax-rules 卫生宏:模式重命名,不捕获调用方名字。

(defmacro swap! (syntax-rules ()
  ((swap! a b) (let [tmp a] (set! a b) (set! b tmp)))))
(def p 1) (def q 2)
(swap! p q)
[p q]

展开可查:macroexpand-1 / macroexpand。

(macroexpand-1 '(my-when false :x))

注意:编译面上,与特殊形式同名的 defmacro 会遮蔽特殊形式(AST/元循环面则拒绝)——不要给宏起特殊形式的名字。