Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid creating temporary scalars when returning multiple arrays

Tags:

raku

Is it possible to avoid creating temporary scalars when returning multiple arrays from a function:

use v6;
sub func() {
    my @a = 1..3;
    my @b = 5..10;
    return @a, @b;
}
my ($x, $y) = func();
my @x := $x;  
my @y := $y;
say "x: ", @x;  # OUTPUT: x: [1 2 3]
say "y: ", @y;  # OUTPUT: y: [5 6 7 8 9 10]

I would like to avoid creating the temporary variables $x and $y. Note: It is not possible to replace the function call with

my (@x, @y) = func()

since assignment of a list to an Array is eager and therefore both the returned arrays end up in @x.

like image 834
Håkon Hægland Avatar asked Feb 03 '23 19:02

Håkon Hægland


1 Answers

Not either of:

my ($x, $y) = func();
my (@x, @y) = func();

But instead either of:

my (@x, @y) := func();
my ($x, $y) := func();

Use @ to signal to P6 that, when it needs to distinguish whether something is singular -- "a single array" -- or plural -- "items contained in a single array" -- it should be treated as plural.

Use $ to signal the other way around -- it should be treated as singular.

You can always later explicitly reverse this by doing $@x -- to signal P6 should use the singular perspective for something you originally declared as plural -- or @$x to signal reversing the other way around.

For an analogy, think of a cake cut into several pieces. Is it a single thing or a bunch of pieces? Note also that @ caches indexing of the pieces whereas $ just remembers that it's a cake. For large lists of things this can make a big difference.

like image 108
raiph Avatar answered Feb 18 '23 10:02

raiph