julia icon indicating copy to clipboard operation
julia copied to clipboard

Dict destructuring syntax

Open simonster opened this issue 11 years ago • 10 comments

It would be nice to have destructuring assignment, so that:

:x=>a, :y=>b = mydict

would be equivalent to:

a = mydict[:x]
b = mydict[:y]

Another proposal, inspired by this JavaScript syntax, is to make =>myvar equivalent to :myvar=>myvar. Especially in combination with destructuring assignment, this would make it easier to move between Associatives and local variables, which would be useful for JLD. But it's possible that this is not a common enough case to be worth the extra syntax.

simonster avatar Sep 29 '14 21:09 simonster

The second one could possibly be done without any syntax changes by doing something like =>(x) = =>(x,x)

PythonNut avatar Oct 14 '14 00:10 PythonNut

@PythonNut That would make =>(myvar) equivalent to myvar=>myvar, not :myvar=>myvar, although perhaps your confusion is a sign that this is too magical. My thought was that, with these proposals together, one could write:

function f()
    x = 1
    y = 2
    z = 3
    Dict(=>x, =>y, =>z)
end

=>x, =>y, =>z = f()
@assert x == 1 && y == 2 && z == 3

simonster avatar Oct 14 '14 00:10 simonster

I see what you're trying to do now... That looks really cool. In your proposal, is this valid?

1=>a, 2=>b = Dict(1 => "a", 2 => "b")
@assert a == "a" && b == "b"

I can't say how convenient =>x = (:x)=>x is, and maybe losing the purity of => as merely a type constructor isn't worth it... but who am I to say?

Of course we can do it with a macro instead...

macro =>(x)
    :($(Expr(:quote,x)) => $x)
end

But of course, at this point the choice of => as the symbol comes into question.

PythonNut avatar Oct 14 '14 00:10 PythonNut

What about the symbol <=> ?

bdeonovic avatar Oct 14 '14 01:10 bdeonovic

If we're going to have a spaceship operator, I'd really want it to mean what it does in Perl, ie x < y ? -1 : y < x ? 1 : 0.

StefanKarpinski avatar Oct 14 '14 02:10 StefanKarpinski

Alright alright, how about <('_'<) ^('_')^ (>'_')> I think that should be fairly clear.

bdeonovic avatar Oct 14 '14 02:10 bdeonovic

@bdeonovic I was trying to parse that... Okay so we have a less than operator overload that takes a string... -__-

Yes, let's reserve the spaceship operator.

PythonNut avatar Oct 14 '14 03:10 PythonNut

Could potentially be expressed with named tuple syntax, once that's a thing.

StefanKarpinski avatar Aug 25 '16 15:08 StefanKarpinski

... and, now named tuple syntax is a thing!

samoconnor avatar Feb 09 '18 00:02 samoconnor

We could have a generic, "de-reference-assignment" operator a =[] b generically equivalent to a = b[a], as well as broadcasted getindex, then the requested feature could just be

(; a = :x, b = :y) .=[] mydict

Maybe a little tortured, but I don't see us ever adding destructuring syntax specifically for dicts.

Keno avatar Nov 28 '25 05:11 Keno