SQL offers a function called coalesce(a, b, c, ...)
that returns null if all of its arguments are null, otherwise it returns the first non-null argument.
How would you go about writing something like this in Clojure?
It will be called like this: (coalesce f1 f2 f3 ...)
where the fi
are forms that should only be evaluated if required. If f1
is non-nil, then f2
should not be evaluated -- it may have side-effects.
Maybe Clojure already offers such a function (or macro).
EDIT: Here a solution that I came up with (modified from Stuart Halloway's Programming Clojure, (and ...)
macro on page 206):
(defmacro coalesce
([] nil)
([x] x)
([x & rest] `(let [c# ~x] (if c# c# (coalesce ~@rest)))))
Seems to work.
(defmacro coalesce
([] nil)
([x] x)
([x & rest] `(let [c# ~x] (if (not (nil? c#)) c# (coalesce ~@rest)))))
Fixed.