I am doing short circuit evaluation as an if then statement. But I am unsure of how it works so that, even if the second term of the “and” operation is not a boolean value, it works and it returns the value (it executes it instead of evaluating it to its true value:
true && (n==2)
Would be a normal use, but in
true && (n=2)
I wonder how it works. I knowthe parentheses are used to indicate precedence of the assignment
Okay, so is it implemented like a?b: false ? Thank you for clarifying. a secondary doubt is, okay, it “returns” (n=2), but it is not a value, but a code. It returns a code to be evaluated. How does Julia handle passing code as a value to be returned and how does it know it needs to evaluate it?
Thank you. My question goes now to the || operator. In that case, it also works with non boolean values. How is that implemented? Is it possible to see how is it implemented by myself?
Personally I’m not a fan of short-circuit for one-line if. Early on with Julia, it became fashionable, perhaps because it occurs a lot in Base and the documentation even advocated for it. Thankfully less recently.
To me a huge selling point of Julia is that it’s readable to non-users almost as pseudo-code. But those unfamiliar with short-circuiting may just go “huh?”
It’s admittedly way less cool to do
if a; b; end # semi-colons unnecessary but easier to parse
but also clearer. If we wanted to be cool there are all sorts of incredible tricks possible with for in C, so why even try with Julia?
I imagine even experienced programmers can occasionally brain-freeze and accidentally mix up || and &&.