在宏中使用循环
Using a loop inside a macro
考虑这个最小的例子
(defmacro foo []
`(list ,@(for [i [1 2 3]] (+ 1 i))))
我希望 (foo)
扩展到 (list 2 3 4)
但是,当我尝试 (macroexpand-1 (foo)
时,我遇到了一堆无法辨认的错误
Syntax error macroexpanding clojure.core/let at (*cider-repl <filepath>:localhost:43203(clj)*:366:22).
test/i - failed: simple-symbol? at: [:bindings :form :local-symbol] spec: :clojure.core.specs.alpha/local-name
test/i - failed: vector? at: [:bindings :form :seq-destructure] spec: :clojure.core.specs.alpha/seq-binding-form
test/i - failed: map? at: [:bindings :form :map-destructure] spec: :clojure.core.specs.alpha/map-bindings
test/i - failed: map? at: [:bindings :form :map-destructure] spec: :clojure.core.specs.alpha/map-special-binding
怎么了?我不能在宏定义中使用 for
循环吗?
,@
应该是 ~@
.
user=> (defmacro foo []
`(list ~@(for [i [1 2 3]] (+ 1 i))))
#'user/foo
user=> (macroexpand-1 '(foo))
(clojure.core/list 2 3 4)
user=> (foo)
(2 3 4)
考虑这个最小的例子
(defmacro foo []
`(list ,@(for [i [1 2 3]] (+ 1 i))))
我希望 (foo)
扩展到 (list 2 3 4)
但是,当我尝试 (macroexpand-1 (foo)
Syntax error macroexpanding clojure.core/let at (*cider-repl <filepath>:localhost:43203(clj)*:366:22).
test/i - failed: simple-symbol? at: [:bindings :form :local-symbol] spec: :clojure.core.specs.alpha/local-name
test/i - failed: vector? at: [:bindings :form :seq-destructure] spec: :clojure.core.specs.alpha/seq-binding-form
test/i - failed: map? at: [:bindings :form :map-destructure] spec: :clojure.core.specs.alpha/map-bindings
test/i - failed: map? at: [:bindings :form :map-destructure] spec: :clojure.core.specs.alpha/map-special-binding
怎么了?我不能在宏定义中使用 for
循环吗?
,@
应该是 ~@
.
user=> (defmacro foo []
`(list ~@(for [i [1 2 3]] (+ 1 i))))
#'user/foo
user=> (macroexpand-1 '(foo))
(clojure.core/list 2 3 4)
user=> (foo)
(2 3 4)