引用与宏
quote 与准引用把代码变数据;defmacro 在求值前变换代码,syntax-rules 给出卫生宏。
quote 让代码变数据;quasiquote(反引号)搭 ,(unquote)与 ,@(splice)写模板(ADR-052:逗号是 unquote 记号)。
'(a (+ 1 2) c)
`(a ,(+ 1 2) c)
(def xs [3 4])
`(0 ,@xs 5)
defmacro 在求值前变换代码。宏接收代码(数据),返回代码。
(defmacro unless [test body]
(list 'if test nil body))
(unless false :ran)
(defmacro infix [a op b]
(list op a b))
(infix 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)
(list p q)
展开过程可查。
(macroexpand-1 '(unless true :x))