tst
tst

Reputation: 1172

Apply `&` on a boolean array

I have an array of boolean values and I want to get the logical and of all elements. What is the most efficient way to do that?

I tried

&([true,false,false]...)

but it throws the error:

syntax: malformed expression

Surprisingly (at least to me) the following expression

|([true,false,false]...)

evaluates to true. So how do I do that? Right now I use a bunch of nots to do that, but this is very unsatisfactory.

Also is this actually better than just looping through all the elements?

Upvotes: 2

Views: 421

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69839

Most probably this behavior of & is caused by deprecated ccall functionality where & was used in front of a variable. As explained in the comments above:

  • you can wrap & in parentheses to make it work as expected(&)([true,false,false]...); however, this is not efficient as you have do splat the passed argument;
  • if your arguments are all Boll then all function is a recommended way to perform logical and;
  • if you would need bitwise and then reduce(&, [true,false,false]) is a nice solution as phg indicated.

Upvotes: 1

Related Questions