Hi All,
I am reviewing The Fast Track to julia. In the Basics section Chaining is mentioned. Three lines of code are:
x = y = z = 1 # right-to-left
0 < x < 3 # true
5 < x != y < 5 # false
It’s the last line that I can’t figure out the logic flow. Can anyone provide me with sufficient details as to how I should evaluate this last line? The Fast Track states it is false as per their comment. I get the same result if I code just the third line and set x=1 and y=1. But if I set x=6 and y=2 it evaluates to true. Any help is greatly appreciated.
dump(:(5 < x != y < 5))
Expr
head: Symbol comparison
args: Array{Any}((7,))
1: Int64 5
2: Symbol <
3: Symbol x
4: Symbol !=
5: Symbol y
6: Symbol <
7: Int64 5
How does this help to understand the behavior of the chaining of the operators?
As an aside, I hope people would avoid this in real code: 5 < x != y < 5 # false
which is difficult for the reader to understand without thinking a minute or even wondering if it’s a bug. It is more a brain-teaser to illustrate chaining, than a recommendation for actual code. The following is clearer and more explicit:
Chaining is great when it’s simple and close to what you’d write with math, as in the first examples above:
x = y = z = 1 # right-to-left
0 < x < 3 # true
The slowest compiler is the human reader, so try to be helpful to them, or even yourself if you ever return to the code months/years later.
As a cranky person, I also avoid the idiomatic
x == y && dosomething()
to avoid an if statement like
if x == y; dosomething(); end
I think the if makes intent clearer and doesn’t assume all readers to understand short-circuiting. (I also prefer the semi-colons even if they can be omitted, just to make it easier to read.) [edit: bug fix]
apo383,
Makes complete sense! A hacker (of the original sense) might appreciate the most minimal code, but mere mortals (me) need readability and ease of comprehension.