Julia: Undocumented behaviour of tuple destructuring

Created on 10 Jul 2019  路  5Comments  路  Source: JuliaLang/julia

Based on the Julia discourse topic Destructuring & setindex!, it seems as if the destructuring of tuples has some nice but undocumented features. Are these intended? If so, a brief documentation would be very helpful.

Example 1 (setindex!):

A = [zeros(2),zeros(3)]
b = fill(0,3)
A[1][1], A[2][2], b[3] = (1, 2, 3)

gives (in 1.2.0-rc2)

julia> A
2-element Array{Array{Float64,1},1}:
 [1.0, 0.0]
 [0.0, 2.0, 0.0]
julia> b
3-element Array{Int64,1}:
 0
 0
 3

Example 2 (recursion):

x,(y,z) = (1, (2,3))  

gives

julia> x
1
julia> y
2
julia> z
3
collections doc

Most helpful comment

It falls out just like all other cases of assignment --- it would be more work to try to prevent it. That said, I would consider that kind of an obfuscated and not-recommended way to define methods. If you want to mention it, I'd recommend against using it. But I prefer to explain how it works and let people enjoy discovering the implications for themselves :)
Here's another good one:

julia> for f() in 1:2
         @show f()
       end
f() = 1
f() = 2

All 5 comments

Sure, this could be clarified in the documentation. It's definitely intended; destructuring is an orthogonal extension of assignment syntax. It never occurred to me that these cases could be considered an extra feature :) Basically there is a rule that a, b = x becomes a = x[1]; b = x[2] (except using iteration), and all other assignment rules are applied recursively.

@PaulSoderlind : I will make a PR, can you reopen it in the meantime so that it is not forgotten?

It is still not clear to me if method definitions are intended, too. Eg as shown by @mbauman,

julia> f(), g(), x+y = 1:3
1:3

julia> f()
1

julia> g()
2

julia> 1+1
3

Should I document this?

It falls out just like all other cases of assignment --- it would be more work to try to prevent it. That said, I would consider that kind of an obfuscated and not-recommended way to define methods. If you want to mention it, I'd recommend against using it. But I prefer to explain how it works and let people enjoy discovering the implications for themselves :)
Here's another good one:

julia> for f() in 1:2
         @show f()
       end
f() = 1
f() = 2

Triage thinks this isn't necessary to add to the documentation. It just logically flows from being on the left hand side of the assignment.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

TotalVerb picture TotalVerb  路  3Comments

Keno picture Keno  路  3Comments

StefanKarpinski picture StefanKarpinski  路  3Comments

dpsanders picture dpsanders  路  3Comments

helgee picture helgee  路  3Comments