向宏添加可选参数
我正在尝试向 Clojure 时间宏添加一个选项“message”属性。基本上我想向时间输出添加可选的自定义消息。我试图找到程序中的瓶颈,并且在时间输出中附加一些描述性消息将非常有帮助。
我已经尝试过以下操作:
;optional argument
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of
expr."
{:added "1.0"}
[expr & msg]
`(let [start# (. System (nanoTime))
ret# ~expr]
(prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs. " (first ~msg)))
ret#))
并且
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of
expr."
{:added "1.0"}
([expr] (time expr ""))
([expr msg]
`(let [start# (. System (nanoTime))
ret# ~expr]
(prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs. " ~msg))
ret#)))
两者都抛出异常。我该如何进行这项工作?
I'm trying to add an option "message" attribute to the Clojure time macro. Basically I want to add an optional custom message to the output of time. I'm trying to find a bottleneck in my program and having some descriptive messages attached to time's output would be very helpful.
I've tried the following:
;optional argument
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of
expr."
{:added "1.0"}
[expr & msg]
`(let [start# (. System (nanoTime))
ret# ~expr]
(prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs. " (first ~msg)))
ret#))
and
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of
expr."
{:added "1.0"}
([expr] (time expr ""))
([expr msg]
`(let [start# (. System (nanoTime))
ret# ~expr]
(prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs. " ~msg))
ret#)))
Both throw exceptions. How do I make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它会引发异常,因为 msg 是一个列表,
假设您使用宏调用它,
宏中的 msg 变成函数调用(“asd”),该函数调用失败。只需解构 msg,
然后使用
您还可以测试如何使用 Macroexpand 扩展宏,
还有几点,
编辑:带有可选消息的时间,
It throws an exception because msg is a list,
say you call it with,
msg in the macro becomes a function call, ("asd") which fails. Just destructure msg,
and use
You can also test how macros are expanded with macroexpand,
Also couple of points,
EDIT: time with optional message,