Why does reduce not work on logical OR

Why does reduce not work on logical OR

julia> a = UInt8[0,2,4,0,5,6,0]
7-element Array{UInt8,1}:
 0x00
 0x02
 0x04
 0x00
 0x05
 0x06
 0x00

julia> b = map(x->x>0,a)
7-element Array{Bool,1}:
 0
 1
 1
 0
 1
 1
 0

julia> reduce(||,b)
ERROR: syntax: invalid identifier name "||"
Stacktrace:
 [1] top-level scope at REPL[27]:0


|| and && in julia are not normal functions. The reason for this is that they short circuit, and the only way to implement this without a macro is to have them not be a normal function. This has several consequences, including this. The other main one is that you can’t define a function called || that does something different. As a solution, you could definefunction or(a,b) =a||b end, which should achieve what you want. However, you also could probably use any which will probably be faster.

3 Likes

Besides the syntax error, IIRC reduce will assume the order of the collection is not important.
Maybe foldl is what you expect.

2 Likes

You can use |

julia> b = [0,2,4,0,5,6,0] .> 0;

julia> reduce(|, b)
true

julia> reduce(&, b)
false

Or maybe it should be foldl, as @thautwarm suggests?

3 Likes