对于练习,我已经定义了
(defmacro quote-paren
"body -> `(body)"
[& body]
`(~@body))
具有预期的转换(quote-paren body)
=> ``(体)`。它似乎满足了一些基本测试:
user=> (macroexpand-1 `(quote-paren 3 4 5))
(3 4 5)
user=> (macroexpand-1 `(quote-paren println "hi"))
(clojure.core/println "hi")
user=> (macroexpand-1 `(quote-paren (println "hi")))
((clojure.core/println "hi"))
但是,我一直用这个do-while宏测试它(从here修改):
(defmacro do-while
[test & body]
(quote-paren loop []
~@body
(when ~test
(recur))))
(def y 4)
(do-while (> y 0)
(def y (dec y)))
但结果是
IllegalStateException Attempting to call unbound fn: #'clojure.core/unquote-splicing clojure.lang.Var$Unbound.throwArity (Var.java:43)
我不明白这一点,因为我可以看到`quote-paren'宏工作得很好(〜@ body插入):
user=> (macroexpand-1
`(quote-paren loop []
(def y (dec y))
(when ~test
(recur))))
(clojure.core/loop [] (def user/y (clojure.core/dec user/y)) (clojure.core/when #<core$test clojure.core$test@1f07f672> (recur)))
但是尝试宏扩展do-while
会导致“unbound fn
”。我有什么微妙的东西吗?
答案 0 :(得分:3)
在quote-paren
user> (defmacro do-while
[test & body]
`(quote-paren loop []
~@body
(when ~test
(recur))))
#'user/do-while
然后正确扩展:
user> (macroexpand '(do-while (> y 0)
(def y (dec y))))
(loop* [] (def y (dec y)) (clojure.core/when (> y 0) (recur)))
似乎有效:
user> (def y 4)
#'user/y
user> (do-while (> y 0)
(def y (dec y)))
nil
user>