Chained comparison evaluation order

This came straight from the official documentation. I don’t understand why v(2) should be evaluated before v(1) in the first example although technically it shouldn’t matter (unlike short circuit operators)… It just seems counterintuitive.

julia> v(x) = (println(x); x)
v (generic function with 1 method)

julia> v(1) < v(2) <= v(3)
2
1
3
true

julia> v(1) < v(2) 
1
2
true

julia> v(2) <= v(3)
2
3
true

For the record, this is different from Python:

>>> def v(x):
...     print(x)
...     return x
... 
>>> v(1) < v(2) < v(3)
1
2
3
True

The evaluation order is undefined and could be changed. You should probably not be counting on side effects from expressions in comparison chains. IIRC, @jeff.bezanson did it this way because it could be implemented slightly more efficiently/easily. That said, I would support making the evaluation order defined and guaranteed left-to-right.

1 Like