Idiomatic clojure conditional function call

I have a clojure function that should pass information to a map if a particular condition is true, using that map as a parameter for another function.

I have the following, but it feels uncomfortable with repeated calls to the bar function.

(defn foo ([opts] (if (= true (something)) (bar (into opts {:ab})) (bar opts))) (def bar [opts]) 

So, if (something) is true, we call additional parameters in the opts parameter before calling the bar function, otherwise we just pass it.

+4
source share
4 answers

The first thing that (= true (something)) can be replaced simply (something) without problems (unless you are actually trying to distinguish between the return value true and the return value, say 1 ). If the return parameters are true and false , (something) by itself will work fine. You can also use merging instead of in, which may be a little clearer.

You can try

 (bar (if (something) (merge opts {:ab}) opts)) 

This would also work, although it requires an unnecessary call to merge when (something) is false, although with nil for the second argument, merge should return very quickly.

 (bar (merge opts (when (something) {:ab}))) 
+7
source

The answer to the answer is all right. It should be noted that if is an expression in Clojure instead of a conditional construct. Therefore, it has a return value, and you can use the return value as a parameter for functions:

 (bar (if (something) (into opts {:ab}) opts)) 

You can think of it as a ternary operator in Java.

+2
source

Implement conditional code on function (s). Sort of:

 (defn addAIfSomethig [opt] (if (something) (into opts {:a "A"}) opt) ) (defn addBIfSomethig [opt] (if (something) (into opts {:b "B"}) opt) ) 

Then in your function, where you need to change the selection function before the call, use the composition function.

 (defn foo [opt] (let [modifiers (comp addAIfSomethig addBIfSomethig)] (bar (modifiers opt)) )) 
0
source

Note that with Clojure 1.5 this can be written

 (cond-> opts (something) (merge {:ab})) 
0
source

Source: https://habr.com/ru/post/1394714/