Michael Deardeuff
Michael Deardeuff

Reputation: 10697

Is there a standard clojure macro for first-not-nil?

I'm am looking for a macro that does effectively the opposite of this maybe-m. That is, I want the result of the first expression that returns non-nil without evaluating the remaining expressions. This last part is important because if the "solution" uses lazy-sequences then they will be evaluated in chunks...meaning the expressions could be evaluated when I don't want them to.

Here's an example of what I'm looking for:

(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

Upvotes: 1

Views: 589

Answers (1)

Jared314
Jared314

Reputation: 5231

Because nil is falsey, or will do what you are looking for.

(defn really-cool-stuff [a b c]
  (or
    (operation1 a b)
    (operation2 b c)
    (operation3 a b c)))

The only exception is if the functions could potentially return false. In that case, you can build a macro that mimics or, except with a more strict conditional.

(defmacro or-nil?
  ([] nil)
  ([x] x)
  ([x & next] `(let [or# ~x] (if (nil? or#) (or-nil? ~@next) or#))))

Upvotes: 9

Related Questions