qiuxiafei
qiuxiafei

Reputation: 5977

Simpler way to judge nil value in (if)?

I often write like the following:

(if (nil? a-value) another-value a-value)

is there a simpler function available like:

(if-nil? a-value another-value)

Upvotes: 2

Views: 105

Answers (2)

Bozhidar Batsov
Bozhidar Batsov

Reputation: 56595

Why not simply define an if-nil? macro:

(defmacro if-nil? [expr body] 
  `(let [e# ~expr] 
    (if (nil? e#) ~body e#)))

Upvotes: 2

mikera
mikera

Reputation: 106351

If you want to use a default value, then the usual idiom is to use the or macro:

(or foo default-value)

Which will return default-value when foo is falsey (nil or false), or foo whenener foo is truthy (i.e. any non-nil value except false).

You can typically also use if-not in such circumstances, since nil is considered to be false. Of course, you need to watch out for actual false values, since these will be treated the same as nil.

As a final option, you can always use a macro to get exactly the if-nil? behaviour you are looking for:

(defmacro if-nil? 
  ([a b] (if-nil? a b nil))
  ([a b c]
    `(if (nil? ~a) ~b ~c)))

Upvotes: 4

Related Questions