alma icon indicating copy to clipboard operation
alma copied to clipboard

Implement postfix:<.=> mutating method call

Open masak opened this issue 9 years ago • 3 comments

I saw someone's Perl 5 code, and realized making a .push on an array with many elements is a very natural thing to do. 007's .push does one element only; if you .push in an array, it ends up as a nested array. (And that's good, IMO. Flattening will get you nowhere.)

Anyway, I was thinking of the use case of pushing in several things and realized .concat does this.

array.concat(otherArray);

But it generates a new array, and doesn't mutate the old one. Again, as it should be. You can write

array = array.concat(otherArray);

But wouldn't it be nice if we could just

array.=concat(otherArray);

Like in Perl 6?

Yes, it would!

Note: this is not exactly the same as pushing several items. You'd get a new reference in array. Somewhere in memory there would be a left-behind, probably-GC-able old unmodified array. But it's close enough, I believe. More to the point, this is how I'd expect .= to behave. In the rare case where we care about keeping the same reference, we can push individual items.

This is in somewhat the same space as #122, in that it also requires us to expose storage locations (lvalues) as an API that macros can use.

masak avatar Oct 26 '16 09:10 masak

Flattening will get you nowhere.

:heart:

I... thought we had that issue already, to be honest.

vendethiel avatar Oct 26 '16 11:10 vendethiel

Yeah, so did I! It might still be in there somewhere, but I did do a thorough scan through the issue queue before I submitted this one. Didn't see it.

masak avatar Oct 26 '16 12:10 masak

I'd like to point out that

array.=concat(otherArray);

has one drawback which matters once in a while: it replaces the value in array with another, newly created array. That is, the old array gets GC'd and a new array with a new reference is created with the concatenated elements.

Luckily, #112 has the fix, and we can implement it the other way as

array.push(*otherArray);

or

array.push(...otherArray);

Depending on which syntax we finally decide on for spread args.

masak avatar May 28 '18 18:05 masak