2010-07-14 48 views
7

以下代码按预期方式执行,但在最后给出NullPointerException。我在这里做错了什么?为什么我会在下面的代码中获得NPE?

(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

回答

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函数的结果,即零。

为了解决这个问题,我建议修改宏以在前面包括“do”,例如,

(defmacro exec-all [& commands] 
    (cons 'do (map (fn [c] `(println "Code: " '~c "\t=>\tResult: " ~c)) commands))) 
+0

+1 jejej,获得使用这些括号:) – OscarRyz 2010-07-14 15:12:02

+0

+1,任何其他方式来解决? – missingfaktor 2010-07-14 15:15:11

+2

当然,你可以重写它以扩大到'doseq'等,但为什么?这是一个完全合理的解决方案,对现有代码的更改很少;我会说坚持下去。 – 2010-07-14 16:19:20

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表单的值将绑定到c的表单会在宏扩展时收集到向量中。

不用说,原始版本更简单,因此我认为(do ...)是完美的解决方案。 :-)

示例交互:

user=> (exec-all (conj [2 3 4] 5) (+ 1 2))                          
Code: (conj [2 3 4] 5) => Result: [2 3 4 5] 
Code: (+ 1 2) => Result: 3 
nil 
+0

+1,谢谢你的回答。 :-) – missingfaktor 2010-07-14 18:13:26

相关问题