您可以在 Tupelo 库中查看带有 the Literate Threading Macro 的示例。我们希望用户输入符号it 并让它被宏识别。这是定义:
(defmacro it->
"A threading macro like as-> that always uses the symbol 'it'
as the placeholder for the next threaded value "
[expr & forms]
`(let [~'it ~expr
~@(interleave (repeat 'it) forms)
]
~'it))
这也称为“照应”宏。然后用户创建如下代码:
(it-> 1
(inc it) ; thread-first or thread-last
(+ it 3) ; thread-first
(/ 10 it) ; thread-last
(str "We need to order " it " items." ) ; middle of 3 arguments
;=> "We need to order 2 items." )
用户在他们的代码中包含特殊符号it,这是宏所期望的(在这种情况下需要&)。
这有点特殊。在大多数情况下,无论用户选择什么符号,您都希望宏能够工作。这就是为什么大多数宏使用(gensym...) 或带有“#”后缀的阅读器版本的原因,如下例所示:
(defmacro with-exception-default
"Evaluates body & returns its result. In the event of an exception, default-val is returned
instead of the exception."
[default-val & body]
`(try
~@body
(catch Exception e# ~default-val)))
这是“正常”情况,宏创建一个“局部变量”e#,保证不会与任何用户符号重叠。一个类似的例子展示了spyx 宏创建了一个名为spy-val# 的“局部变量”来临时保存表达式expr 的计算结果:
(defmacro spyx
"An expression (println ...) for use in threading forms (& elsewhere). Evaluates the supplied
expression, printing both the expression and its value to stdout, then returns the value."
[expr]
`(let [spy-val# ~expr]
(println (str (spy-indent-spaces) '~expr " => " (pr-str spy-val#)))
spy-val#))
请注意,对于 (println...) 语句,我们看到了与 '~expr 相反的语法——但这是另一天的话题。