【发布时间】:2014-01-01 03:23:44
【问题描述】:
我的困惑是下面的例子:
(defmacro macro1 [x]
(println x))
(defn func1 [x]
(println x))
(defmacro macro2 [x]
`(macro1 ~x)
(func1 x))
(defmacro macro3 [x]
(func1 x)
`(macro1 ~x))
(println "macro2")
(macro2 hello)
(println "macro3")
(macro3 hello)
令人惊讶的是,输出是:
macro2
hello
macro3
hello
hello
为什么macro2和macro3的输出不一样?在我的理解中,所有宏内部的宏调用都可以用函数代替(重用的原因除外)。我的理解有什么问题吗?
感谢迈克尔的澄清。我的一般问题是如何选择在宏内部使用函数或宏来操作 s 表达式。我想知道它们是否可以互换使用,除非它们在不同阶段进行评估。另一个例子:
(defn manipulate-func [x]
(list + x 1))
(defmacro manipulate-macro [x]
(list + x 1))
(defmacro macro1 [x y]
[(manipulate-func x) `(manipulate-macro ~y)])
(println (clojure.walk/macroexpand-all '(macro1 (+ 1 2) (+ 3 4))))
;; [(#<core$_PLUS_ clojure.core$_PLUS_@332b9f79> (+ 1 2) 1) (#<core$_PLUS_ clojure.core$_PLUS_@332b9f79> (+ 3 4) 1)]
【问题讨论】: