If condition with a vector comparison

Hello, im trying to make a if condition where I can compare a variable to any value of vector and if it matches to any condition, it counted as true…

Example:

a = 3

if a == any([1, 2, 3, 4])  # imaginary function any() which will be more like a iterator..

   print("true")

else
 
  print("false")

end

Is there a function like any() in this example?

Thank you

Yes! It is called any :slight_smile:

any(a .== [1, 2, 3, 4])

The line above uses broadcasting to compare a to each of the listed numbers. As a result, the argument of any is a vector of Bool values, and any returns true if the argument collection contains any true.

This is probably the most straightforward way, but not the most efficient.

Another way is to use

any(==(a), [1,2,3,4])
# or equivalently
any([1,2,3,4]) do x
    x == a
end

which does the same thing but avoids creating the intermediate vector of Bools.

EDIT: Haha, @lmiq’s suggestion is definitely better if you are interested in equality comparison. Use any when the condition is not equality.

3 Likes
a in [1,2,3,4]

a in 1:4

?

3 Likes

Am I doing something wrong here ? its not printing - yes.

a = 3
if a in [1, 2, 3, 4] == true
           print("yes")  
else 
          print("no")
end

this works

if any(a .== [1, 2, 3, 4]) == true
           print("yes") 
 else  
          print("false")
end

It’s about operator precedence. The condition is evaluated as

a in ([1, 2, 3, 4] == true)

not as

(a in [1, 2, 3, 4]) == true

You can simply use

a = 3
if a in [1, 2, 3, 4]
    print("yes")  
else 
    print("no")
end
4 Likes

thank you @barucden and @lmiq for help :).

It’s not just about operator precedence, though. If you have a boolean condition, for example mycond, you should not write

if mycond == true
    # do something
end

The == true part is redundant, and not considered idiomatic. You should always just write

if mycond
    # do something
end

or

if !mycond  # this means that mycond is false
    # do something else
end

Any time you see == true or == false, you should consider whether something is off.

2 Likes