我正在寻找一个与此相反的宏maybe-m
.也就是说,我希望第一个表达式的结果返回非nil 而不评估剩余的表达式.最后一部分很重要,因为如果"解决方案"使用延迟序列,那么它们将以块的形式进行评估...这意味着可以在我不希望它们时评估表达式.
这是我正在寻找的一个例子:
(defn really-cool-stuff [a b c]
(first-not-nil
(operation1 a b) ; <-- this returns nil,
(operation2 b c) ; <-- this returns non-nil, the result is returned
(operation3 a b c))) ; <-- this is not evaluated
Run Code Online (Sandbox Code Playgroud)
因为nil
是假的,or
会做你想要的.
(defn really-cool-stuff [a b c]
(or
(operation1 a b)
(operation2 b c)
(operation3 a b c)))
Run Code Online (Sandbox Code Playgroud)
唯一的例外是函数是否可能返回false
.在这种情况下,您可以构建一个模仿的宏or
,除了更严格的条件.
(defmacro or-nil?
([] nil)
([x] x)
([x & next] `(let [or# ~x] (if (nil? or#) (or-nil? ~@next) or#))))
Run Code Online (Sandbox Code Playgroud)