Multiple Assignment (and A Little Destructuring)
Multiple Assignment
Currently multiple assignment is implemented in Onyx like this:
[a, b, c, d] = [1, 2, 3, 4] -- => a=1,b=2,c=3,d=4
[a, c, b, d] = [a+1, b, c, d+1] -- => a=2,b=3,c=2,d=5
x = 1
y = 2
[x, y] = [y, x] -- => x = 2, y = 1
foo(x) ->
a = 3
{x, 2, a}
[a,b,c] = foo(1) -- => a=1,b=2,c=3
- For the literal source case (array style literal), it's broken out to direct assigns immediately.
- The source can be any indexable (sequence, array, listish, tuple, etc.)
Thoughts
- It would arguebly be better to do full blown deconstruction. The pro of
[a,b...] =notation is that you don't have to care about what's on the right, as long as it is indexable. Perhaps at least both[...] =ad{...} =should be allowed, to enable expressing intent clearer. - Splats and discard should be added. This is no biggie, just a matter of getting time prioritized to code it:
[a, _, ...some-b, c] = [1,2,3,4,5,6]=> a=1, some-b=[3,4,5], c=6 (2 is thrown away).- This is where destructuring choice of notation comes into play, splat will be a sequence here, maybe we wanted array or tuple, or... Perhaps it should just default to the type on the right.
Destructuring
- Destructuring hash(-trees) is another interesting thing to tackle.
{foo: a, bar: [_, b]} = {foo:"hey", bar: ["world", "baby"]}=> a="hey", b="baby"- But then again - at some level, sugary notations like these becomes diabetes instead, and perhaps it's better for readability to just break it down in to individual accesses. - So hash-tree destructuring, has a thumbs down from me currently, even if "cool in concept".
- Destructuring notation is important for types also, if a full blown pattern matching construct is wanted (it seems like a good idea). So this is tied in to the
matchcase-switch-what-you-prefer-to-call-it construct too.- Type-destructuring differs in that there are less dynamics in place (known at compile time)
t would arguebly be better to do full blown deconstruction. The pro of [a,b...] = notation is that you don't have to care about what's on the right, as long as it is indexable. Perhaps at least both [...] = ad {...} = should be allowed, to enable expressing intent clearer.
I don't understand.
Perhaps it should just default to the type on the right.
I don't see why not.
I like the idea of hash destructuring.
-
I was referring to when multi-assigning from say a List or a Tuple, the ability to use the "matching" literal in the left part to reflect the type on the right part (aside from the fact that
{}"shouldn't" have anything to do with tuples, but...) - hmmm, did it make it clearer? -
Yeah, I guess it kinda was the obvious thing to do, using the right-hand type for the splat that is.
I think full deconstruction would be nice.
What happens if the given key is not present in the hash though?
{firstname: b} = {name: "fred"} -- crash?