Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check multiple conditions on the same function output in Julia

Tags:

julia

Is there a way to check multiple Boolean conditions against a value (to achieve the same as below) without computing sum twice or saving the result to a variable?

if sum(x) == 1 || sum(x) > 3
    # Do Something
end
like image 344
Nathan Boyer Avatar asked Nov 30 '25 12:11

Nathan Boyer


2 Answers

You can use one of several options:

Anonymous function:

if (i->i>3||i==1)(sum(x))
    # Do Something
end

Or,

if sum(x) |> i->i>3||i==1
    # Do Something
end

DeMorgan's theorem:

if !(3 >= sum(x) != 1)
    # Do Something
end

And if used inside a loop:

3 >= sum(x) != 1 && break
# Do Something

or as function return:

3 >= sum(x) != 1 && return false

But using a temporary variable would be the most readable of all:

s = sum(x)
if s > 3 || s == 1
    # Do Something 
end
like image 165
AboAmmar Avatar answered Dec 03 '25 03:12

AboAmmar


Syntactically, a let is valid in that position, and the closest equivalent to AboAmmar's variant with a lambda:

if let s = sum(x)
       s == 1 || s > 3
   end
   # do something
end

I'd consider this rather unidiomatic, though.

like image 26
phipsgabler Avatar answered Dec 03 '25 02:12

phipsgabler



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!