【发布时间】:2012-10-22 23:24:28
【问题描述】:
在我的 Clojure 共享源中,我有以下内容(我无耻地偷了):
(defmacro hey-str [name]
`(str "hey " ~name))
{:author "Laurent Petit (and others)"
:doc "Functions/macros variants of the ones that can be found in clojure.core
(note to other contrib members: feel free to add to this lib)"}
(defmacro- defnilsafe [docstring non-safe-name nil-safe-name]
`(defmacro ~nil-safe-name ~docstring
{:arglists '([~'x ~'form] [~'x ~'form ~'& ~'forms])}
([x# form#]
`(let [~'i# ~x#] (when-not (nil? ~'i#) (~'~non-safe-name ~'i# ~form#))))
([x# form# & more#]
`(~'~nil-safe-name (~'~nil-safe-name ~x# ~form#) ~@more#))))
(defnilsafe
"Same as clojure.core/-> but returns nil as soon as the threaded value is nil itself (thus short-circuiting any pending computation).
Examples :
(-?> \"foo\" .toUpperCase (.substring 1)) returns \"OO\"
(-?> nil .toUpperCase (.substring 1)) returns nil
"
-> -?>)
(defnilsafe
"Same as clojure.core/.. but returns nil as soon as the threaded value is nil itself (thus short-circuiting any pending computation).
Examples :
(.?. \"foo\" .toUpperCase (.substring 1)) returns \"OO\"
(.?. nil .toUpperCase (.substring 1)) returns nil
"
.. .?.)
(defnilsafe
"Same as clojure.core/->> but returns nil as soon as the threaded value is nil itself (thus short-circuiting any pending computation).
Examples :
(-?>> (range 5) (map inc)) returns (1 2 3 4 5)
(-?>> [] seq (map inc)) returns nil
"
->> -?>>)
在我的 Clojurescript 代码中,我有以下内容(I :require-macros as c)
(def a nil)
(def b [])
(def c [{:a 23}])
(js/alert (c/hey-str "Stephen")) ;; should display "hey Stephen"
(js/alert (c/-?> a first :a)) ;; should display nil
(js/alert (c/-?> b first :a)) ;; should display nil
(js/alert (c/-?> c first :a)) ;; should display 23
不幸的是,当我编译时,我得到:
WARNING: Use of undeclared Var webstack.client/-?> at line 56 cljs-src/webstack/client.cljs
WARNING: Use of undeclared Var webstack.client/-?> at line 57 cljs-src/webstack/client.cljs
WARNING: Use of undeclared Var webstack.client/-?> at line 58 cljs-src/webstack/client.cljs
当我在浏览器中打开 javascript 时,我收到“嘿斯蒂芬”警报对话框,但在“嘿斯蒂芬”警报。果然,看看生成的javascript代码,我的js/alert就变成了:
alert([cljs.core.str("hey "), cljs.core.str("Stephen")].join(""));
alert(webstack.client.__QMARK__GT_.call(null, webstack.client.__QMARK__GT_.call(null, webstack.client.a, cljs.core.first), "\ufdd0'a"));
alert(webstack.client.__QMARK__GT_.call(null, webstack.client.__QMARK__GT_.call(null, webstack.client.b, cljs.core.first), "\ufdd0'a"));
alert(webstack.client.__QMARK__GT_.call(null, webstack.client.__QMARK__GT_.call(null, webstack.client.c, cljs.core.first), "\ufdd0'a"))
很明显,我可以使用宏,但是 -?> (和相关)宏的编写方式导致它们无法编译。我需要做什么才能使用这些 -?> .?. 和 `-?>>' 宏?
【问题讨论】:
-
您可以尝试为 nil-safe-name 创建一个宏(从 defnilsafe 宏)而不是创建一个函数吗?
-
@Ankur 不,它必须是一个宏,因为它的表达式需要在评估之前的编译/宏扩展时间安排。
-
@rplevy:我说的是宏是在创建另一个宏,而不是宏可以创建一个函数
-
@Ankur 你如何将
-?>写成函数? -
@Ankur 这是一个反问。正确的答案是,你不能。
标签: clojure clojurescript