Search code examples
if-statementclojure

Clojure: Multiple tasks in if


As I've come to know it, the form of an if is (if [condition] [true] [false]). Similarly, cond is (cond [condition] [true] ... [condition] [true] [false]). Each true and false segment seems to only accept one action. If I want to represent the following logic:

if (i > 0)
{
    a += 5;
    b += 10;
}

I think I have to do:

(if (> i 0) (def a (+ a 5)))
(if (> i 0) (def b (+ b 10)))

Just so the second action isn't confused as a false result. Is this how it needs to be, or is there a way to create a larger body for an if?

p.s. I also suspect redefining a and b each time isn't the best way to increment, but also haven't seen a different way of doing that. I've had to also redefine lists when using conj.


Solution

  • The most direct transaction, using atoms instead of vars (def), would be

    ;; assuming something like (def a (atom 0)) (def b (atom 0))
    (if (> i 0)
      (do
        (swap! a + 5)
        (swap! b + 10)))
    

    or

    (when (> i 0)
      (swap! a + 5)
      (swap! b + 10))