[ACCEPTED]-In Clojure how to choose a value if nil-clojure

Accepted answer
Score: 101

just use or:

(or input-argument "default")

0

Score: 23

Alex's suggestion of "or" is indeed the 4 idiomatic way to rewrite your example code, but 3 note that it will not only replace nil values, but 2 also those which are false.

If you want to keep 1 the value false but discard nil, you need:

(let [val (if (nil? input-argument) "use default argument" input-argument)]
   ...)
Score: 7

If you only bind the variable to do get 15 the right value and not to use it twice 14 there is a other way you can do it. There 13 is a function in core called fnil.

You call 12 fnil with the function you want to call and 11 the default argument. This will return a 10 function that will replace nils with the 9 default value you provided.

The you can do 8 one of the things depending on what you 7 want. Creat a local function.

(let [default-fn (fnil fn-you-want-to call "default-argument")]
(default-fn input-argument))

In somecases 6 (where you always have the same default 5 argument) you can move to logic to do this 4 out of your code and put it where to original 3 function was (or wrap the function in case 2 it in a other library).

(defn fn-you-want-to-call [arg] ....)
(def fn-you-want-to-call-default (fnil fn-you-want-to-call "default-argument"))

Then in your code 1 its reduced to just

(fn-you-want-to-call-default input-argument)

More you can find here: http://clojuredocs.org/clojure_core/clojure.core/fnil

More Related questions