在Clojure中,你可以使用函数 (defn coalesce [& options] (first (remove nil? options)))
来实现类似于SQL中的 coalesce(a, b, c, ...)
函数。如果所有参数都是null,则返回null,否则返回第一个非null参数。调用方式为 (coalesce f1 f2 f3 ...)
,其中 fi
是需要计算的表达式,只有在需要时才会被计算,在此之前将不会评估 f2
,因为它可能具有副作用。Clojure中也许已经有了这样的函数(或宏)。
编辑:以下是我想出来的解决方案(改编自 Stuart Halloway 的《Programming Clojure》,第206页上的(and ...)
宏):
(defmacro coalesce
([] nil)
([x] x)
([x & rest] `(let [c# ~x] (if c# c# (coalesce ~@rest)))))
看起来能够工作。
(defmacro coalesce
([] nil)
([x] x)
([x & rest] `(let [c# ~x] (if (not (nil? c#)) c# (coalesce ~@rest)))))
已修复。
(or ...)
正好符合我的需求。我没有意识到(and ...)
和(or ...)
会返回值。我以为它们会返回false或true。但即使这些也不能返回我想要的false
输入的值。 - Ralph