以下代码按预期执行,但最后给出NullPointerException
。我在这里做错了什么?
(ns my-first-macro)
(defmacro exec-all [& commands]
(map (fn [c] `(println "Code: " '~c "\t=>\tResult: " ~c)) commands))
(exec-all
(cons 2 [4 5 6])
({:k 3 :m 8} :k)
(conj [4 5 \d] \e \f))
; Output:
; Clojure 1.2.0-master-SNAPSHOT
; Code: (cons 2 [4 5 6]) => Result: (2 4 5 6)
; Code: ({:k 3, :m 8} :k) => Result: 3
; Code: (conj [4 5 d] e f) => Result: [4 5 d e f]
; java.lang.NullPointerException (MyFirstMacro.clj:0)
; 1:1 user=> #<Namespace my-first-macro>
; 1:2 my-first-macro=>
(如果语法高亮显示正确的代码,请转到here。)
答案 0 :(得分:11)
看看正在发生的扩张:
(macroexpand '(exec-all (cons 2 [4 5 6])))
=>
((clojure.core/println "Code: " (quote (cons 2 [4 5 6])) "\t=>\tResult: " (cons 2 [4 5 6])))
如您所见,扩展周围有一对额外的括号,这意味着Clojure尝试执行println函数的结果,即nil。
要解决此问题,我建议修改宏以在前面加上“do”,例如
(defmacro exec-all [& commands]
(cons 'do (map (fn [c] `(println "Code: " '~c "\t=>\tResult: " ~c)) commands)))
答案 1 :(得分:6)
由于OP要求其他可能的方法来编写这个宏(请参阅对已接受答案的评论),这里有:
(defmacro exec-all [& commands]
`(doseq [c# ~(vec (map (fn [c]
`(fn [] (println "Code: " '~c "=> Result: " ~c)))
commands))]
(c#)))
这扩展到类似
(doseq [c [(fn []
(println "Code: " '(conj [2 3 4] 5)
"=> Result: " (conj [2 3 4] 5)))
(fn []
(println "Code: " '(+ 1 2)
"=> Result: " (+ 1 2)))]]
(c))
请注意,其值将绑定到fn
的{{1}}表单会在宏展开时收集到向量中。
毋庸置疑,原始版本更简单,因此我认为c
是完美的解决方案。 : - )
互动示例:
(do ...)