How to call the "logical and" operator as a function?

We can call the add operator as Base.:+. Can I do the same to logical and?

julia> Base.:+(3, 4)
7

julia> Base.:&&(true, false)
ERROR: UndefVarError: && not defined
Stacktrace:
 [1] getproperty(x::Module, f::Symbol)
   @ Base .\Base.jl:31
 [2] top-level scope
   @ REPL[7]:1

julia> true && false
false

I don’t think so.
Because && is actually control flow, like if or ? not simply a function like + is.
Due to having short-circuiting behavior

3 Likes

You can use the function all, for instance all([true,false]).

1 Like

Thanks. I actually want the Boolean operators: and, or, not.

Interestingly, I just realized that the bitwise operations can work here.

julia> Base.:&(1, 0)
0

julia> Base.:&(1, 1)
1

julia> Base.:&(true, false)
false

julia> Base.:&(true, true)
true

julia> Base.:~(true)
false

julia> Base.:|(true, true)
true

julia> Base.:|(true, false)
true
2 Likes

ah yes, the when applied to Bools bitwise & is exactly equal to “logical and”

As has been vaguely hinted, the issue here is that && and || are actually control flow constructs (like if) rather than functions (like +). But yes, some combination of &, |, all, and any is what you’re after.

Of course, you can always make your own functions if you need. For example, (x,y) -> x && y would have worked. But you should obviously just use Base.:& here, and new functions will not allow you to extend do not change the behavior of Base.:& to new types change the behavior of Base.:& (edited for clarity).

2 Likes

Not sure I follow - you’re very much able to define methods on new types for &. It’s a function like any other.

2 Likes