当我重新实现用Clojure在Scheme中编写的宏时,我遇到了麻烦。
宏尝试将测试数据对加载到all-tests
var中供以后使用。
因为宏的参数是可变长度并且包含特殊的未定义符号,即=>
,所以我根本不知道如何像Scheme语法规则那样解析它。
计划版本:
(define all-tests '())
;;; load tests into all-tests
(define-syntax add-tests-with-string-output
(syntax-rules (=>)
[(_ test-name [expr => output-string] ...)
(set! all-tests
(cons
'(test-name [expr string output-string] ...)
all-tests))]))
(add-tests-with-string-output "integers"
[0 => "0\n"]
[1 => "1\n"]
[-1 => "-1\n"]
[10 => "10\n"]
[-10 => "-10\n"]
[2736 => "2736\n"]
[-2736 => "-2736\n"]
[536870911 => "536870911\n"]
[-536870912 => "-536870912\n"]
)
我目前不成功的Clojure版本:
(def all-tests (atom '()))
(defmacro add-tests-with-string-output
[test-name & body]
`(loop [bds# (list body)]
(when-not (empty? bds#)
(println (first bds#))
(recur (rest bds#)))))
Ps:我正在使用println
来测试我的代码。当它工作时,我将尝试进行解析和加载工作。
答案 0 :(得分:1)
第一个宏形成一个循环,第二个宏形成doseq
(因此更简单)。两者都应该表现相同。此外,我发现从宏中提取尽可能多的逻辑到辅助功能是个好主意。函数更容易调试,测试和写入。如果宏稍微复杂一些,我可能会留下更少的逻辑。
(def all-tests (atom '()))
(defn add-test [test-name expr output-string]
(swap! all-tests #(cons (list test-name [expr output-string]) %)))
(defmacro add-tests-with-string-output
[test-name & body]
;`(loop [bds# '(~@body)]
`(loop [bds# '~body] ; edit
(when-not (empty? bds#)
(let [bd# (first bds#)
expr# (first bd#)
output-string# (last bd#)]
(add-test ~test-name expr# output-string#)
(recur (rest bds#))
))))
(defmacro add-tests-with-string-output2
[test-name & body]
;`(doseq [bd# '(~@body)]
`(doseq [bd# '~body] ; edit
(let [expr# (first bd#)
output-string# (last bd#)]
(add-test ~test-name expr# output-string#))))
user=> (add-tests-with-string-output "test1" [0 => "0\n"] [1 => "1\n"])
nil
user=> (add-tests-with-string-output2 "test2" [0 => "0\n"] [1 => "1\n"])
nil
user=> @all-tests
(("test2" [1 "1\n"]) ("test2" [0 "0\n"]) ("test1" [1 "1\n"]) ("test1" [0 "0\n"]))
答案 1 :(得分:0)
经过试验和错误,最后我弄清楚如何解决它。
首先使用 Destructuring 来处理变长的参数;
以后不要在宏中使用语法 - 引用,即反引用`,因为如果是这样,一旦你需要取消引用~
参数,即body
,你将获得由于特殊符号=>
:
CompilerException java.lang.RuntimeException:无法解析 符号:=>在这种情况下
以下是我的解决方案。 如果你变得更好,或者你知道Syntax-Quote和Unquote出错的原因,请告诉我。
;;; load tests into all-tests
(def all-tests (atom '()))
(defmacro add-tests-with-string-output
[test-name & body]
(loop [bds body, tests '()]
(if (empty? bds)
(do
(swap! all-tests #(cons (cons test-name tests) %))
nil)
(let [pair (first bds),
input (first pair)
output (last pair)]
(recur (rest bds) (cons (list input ''string output) tests))))))