Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 854
buddingprogrammer Avatar asked Oct 17 '25 06:10

buddingprogrammer


1 Answers

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))
like image 120
gfredericks Avatar answered Oct 20 '25 22:10

gfredericks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!