I have a clojure function that needs to push information into a map if a particular condition is true, using that map as a parameter for another function.
I have the following, but it feels clumsy with the repeated calls to the bar function.
(defn foo ([opts]
(if (= true (something))
(bar (into opts {:a b}))
(bar opts)))
(def bar [opts])
So if (something) is true, we push extra options into the opts parameter before calling the bar function, otherwise we just pass it through.
First thing is that (= true (something))
can be replaced simply by (something)
with no issues (unless you are actually trying to differentiate between a return value of true
and a return value of, say, 1
). If the options for the return value are true
and false
, (something)
by itself will work fine. You can also use merge instead of into, which might be slightly clearer.
You could try
(bar (if (something)
(merge opts {:a b})
opts))
This would work as well, though it involves calling merge
unnecessarily when (something)
is false, though with nil
for the second argument, merge
should return very quickly.
(bar (merge opts
(when (something)
{:a b})))
retief's answer is all right. It should be noted that if
is an expression in Clojure instead of just a conditional construct. Therefore, it has a return value and you can use the return value as a parameter to functions:
(bar (if (something)
(into opts {:a b})
opts))
You can think of it as the ternary operator in Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With