Unexpected result from short-circuiting (inline if)

This looks like a nice one to add to Syntax Surprises.

Observe:

julia> a = 1, 2
(1, 2)

julia> a = (1, 2)
(1, 2)

julia> (a = (1, 2))
(1, 2)

julia> (a = 1, 2)
ERROR: syntax: invalid named tuple element "2" around REPL[228]:1

The basic idea is: in most circumstances, you should expect to have to wrap Tuples in parentheses; excluding the parentheses for standalone assignment statements is the exception, not the rule.

Within parentheses, = binds more tightly than comma—this allows NamedTuples to be formed. Namely, we get to make these:

julia> (a=1, b=2)
(a = 1, b = 2)

But, it comes with the drawback of somewhat unintuitive parsing rules, where the binding tightness of = depends on whether it’s wrapped in parentheses or not.

To illustrate how this influences your case:

julia> b = [0, 0];

julia> if true; b .= (1, 2) end;  b
2-element Vector{Int64}:
 1
 2

julia> true && (b .= 1, 2)
([1, 1], 2)

julia> b
2-element Vector{Int64}:
 1
 1

julia> true && (b .= (1, 2));  b
2-element Vector{Int64}:
 1
 2
8 Likes