Short Circuit Evaluation
In the post Boolean Algebra, we had talked about using
& to Boolean AND stuff and using
| to Boolean OR. But there is one draw back. If I say
false & true, just by looking at
false & one can say the result is
false, irrespective of what is on the right side operand, but this
& looks at its both left and right side anyway. There is however are two intelligent and operators that Julia calls as short cut evaluation, one of them is
&&, a double AND.
If there is an expression
false && true, Julia seeing
false &&, doesn’t bother what’s at the right side if the
&& and just returns false. It saves valuable computing power. In Data Science applications we use very simple algorithms with massive amounts of data, so computing efficiency is important, so Julia is a good candidate for it. It is also possible to write very inefficient programs in Julia if one is not careful. So I feel these kind of small knowledge tidbits are useful.
So lets see a program with double AND
&& short cut operator. Below program checks which of the three given variables have the highest values and prints them out. Note how we have used
&& operators everywhere.
a = 6; b = 7; c = 7 if a > b && a > c println("a = ", a, " is the greatest") elseif b > a && b > c println("b = ", b, " is the greatest") elseif c > a && c > b println("c = ", c, " is the greatest") else println("All or some variables have equal value") end
All or some variables have equal value
So if you take the line
if a > b && a > c, when
a > b is false, Julia does not compare
c in ` a > c`. That’s bit smart and if this program is running billion times on say 50 data crunching servers, it makes a difference.
Similarly we have a double pipe symbol
|| used for OR operations. So if there is
true || false situation, Julia never bothers what’s at the right side of
||, it just returns
true. Below is a program that takes weather input, if the weather is
"rainy", it tells you to take an umbrella, else it says its a nice weather.
weather = "sunny" if (weather == "sunny") || (weather == "rainy") println("Take an umbrella") else println("Looks like nice weather") end
Take an umbrella
The notebook for this blog is available here https://gitlab.com/data-science-with-julia/code/-/blob/master/short_circuit_evaluation.ipynb.