为什么我的 clojurescript 宏不起作用
Why is my clojurescript macro not working
我需要 when-not-empty-let
类似于 clojure/core
的 when-let
. So, I've just added not-empty
call to when-let
macro from clojure's source code 的宏:
(defmacro when-not-empty-let
"bindings => binding-form test
When test is not empty, evaluates body with binding-form bound to the value of test"
[bindings & body]
(.log js/console "check")
(let [form (first bindings) tst (second bindings)]
`(let [temp# ~tst]
(when (not-empty temp#)
(let [~form temp#]
~@body)))))
(也将 (bindings 0)
替换为 (first bindings)
,否则无法编译)
我是这样使用的:
(defn something
[]
(when-not-empty-let [foo ["foo"]]
(.log js/console foo)))
(something)
我得到以下输出:
undefined
check
我做错了什么?
使用 Clojure v1.9.0 构建,ClojureScript:v1.10.126,lein-cljsbuild:v1.1.7
在 Chrome v59.0.3071.115 中测试 Ubuntu。
更新: 重现问题的 jsbin(至少对我而言):https://jsbin.com/liluwer/1/edit?js,output
在浏览器的开发人员工具控制台中查看问题的输出。
There is a strict rule for when you can use defmacro -- you can only use it in what we call a macro namespace, effectively forcing you to separate your compile time and runtime code.
错误是我试图在同一个命名空间中测试宏。
我需要 when-not-empty-let
类似于 clojure/core
的 when-let
. So, I've just added not-empty
call to when-let
macro from clojure's source code 的宏:
(defmacro when-not-empty-let
"bindings => binding-form test
When test is not empty, evaluates body with binding-form bound to the value of test"
[bindings & body]
(.log js/console "check")
(let [form (first bindings) tst (second bindings)]
`(let [temp# ~tst]
(when (not-empty temp#)
(let [~form temp#]
~@body)))))
(也将 (bindings 0)
替换为 (first bindings)
,否则无法编译)
我是这样使用的:
(defn something
[]
(when-not-empty-let [foo ["foo"]]
(.log js/console foo)))
(something)
我得到以下输出:
undefined
check
我做错了什么?
使用 Clojure v1.9.0 构建,ClojureScript:v1.10.126,lein-cljsbuild:v1.1.7
在 Chrome v59.0.3071.115 中测试 Ubuntu。
更新: 重现问题的 jsbin(至少对我而言):https://jsbin.com/liluwer/1/edit?js,output
在浏览器的开发人员工具控制台中查看问题的输出。
There is a strict rule for when you can use defmacro -- you can only use it in what we call a macro namespace, effectively forcing you to separate your compile time and runtime code.
错误是我试图在同一个命名空间中测试宏。