trzczy
trzczy

Reputation: 1481

Combining "if-let" with "OR" so functions may be executed several times on one value

What I am trying to achieve is to execute functions on a value several times when several conditions are met. In particular say we have two variables a and b.

When a is true the value is transformed by the function associated to a, then when b is true the new value is transformed by the function associated to b.

So when the initial value is 0 and the functions are inc and #(+ 5 %) we can get 0, 1, 5 or 6.

My approach was as following but not succeed

user> (def initial-number 0)
user> (if-let [a true b true] (cond-> initial-number a inc b (#(+ 5 %))))
IllegalArgumentException clojure.core/if-let requires exactly 2 forms in binding vector in user:  clojure.core/if-let (core.clj:1758)
user>

Upvotes: 0

Views: 96

Answers (1)

dpassen
dpassen

Reputation: 1306

The code you have will work as described if you substitute if-let for let. All of your conditional logic exists within the cond->.

(def initial-number 0)

(let [a true  b true]  (cond-> initial-number a inc b (#(+ 5 %)))) => 6
(let [a false b true]  (cond-> initial-number a inc b (#(+ 5 %)))) => 5
(let [a true  b false] (cond-> initial-number a inc b (#(+ 5 %)))) => 1
(let [a false b false] (cond-> initial-number a inc b (#(+ 5 %)))) => 0

Upvotes: 3

Related Questions