在 clojure 中,如何编写类似 defn 的宏,其中函数将在第一次失败时退出?
在 clojure 中,我想编写一个 defn-my
宏来创建一个带有 body
的函数。当执行此函数时,它会在第一个不返回 0 的语句处退出。
例如:
(defn f1[] (println "f1") 5)
(defn f2[] (println "f2") 0)
(defn-my foo[] (f1) (f2))
(defn-my bar[] (f2) (f1))
(foo); should execute f1 and exit
(bar); should execute f2 and then f1
In clojure, I would like to write a defn-my
macro that creates a function with a body
. And when this function is executed, it exits on first statement that doesn't return 0.
For example:
(defn f1[] (println "f1") 5)
(defn f2[] (println "f2") 0)
(defn-my foo[] (f1) (f2))
(defn-my bar[] (f2) (f1))
(foo); should execute f1 and exit
(bar); should execute f2 and then f1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您要求的是这样的:
宏假设每个表达式的计算结果都是一个数字。例如,如果表达式的计算结果为
nil
,它将引发异常。然后你可以这样写
defn-my
:I think you are asking for something like this:
The macro assumes every expression evaluates to a number. It will throw an exception if, for example, an expression evaluates to
nil
.Then you can write yout
defn-my
like this:只需利用
and
的短路行为即可:结果:
使用
or
可以获得相反的行为,在第一个非零处终止。Just leverage the short-circuit behaviour of
and
:Results:
You can get the opposite behaviour, terminating on first non-nil, with
or
.