false are quintessential to computer programming. Let’s describe the basic boolean operations implemented in Julia:
||returns the opposite of x|
||returns true if both operands are true|
||returns true if at least one of the operands is true|
|| are short-circuited (see Wiki).
This has a series of advantages. In particular, we can do
if a > 0 && expensive_computation(b) > 0 do_something() end
In this way, we avoid performing the expensive computation if it’s not necessary (when
Also, you won’t get a nasty error when doing something like
if @isdefined(ge) && ge>0 print("ge exists and is greater than 0") end
because trying to assess whether an undefined variable is greater than zero is usually not permitted in any programming language. If the variable is not defined, the second condition won’t be checked.
As for the
or operator, the fact that it is short-circuited means that it will return
true if the first expression is
true without the need to evaluate the second expression. This can also lead to performance gains.
if 3 > 2 || expensive_computation(b) > 0 do_something() end
expensive_computation function won’t be called, as the first expression returnes
Logical to Number
Bool is a subtype of
true equals 1, while
false equals zero. In particular, we can do numerical operations on
Bool types without the need of any type conversion.
true + true # 2