Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shorten an array in Perl 6?

Tags:

arrays

raku

How could I cut off an array or an array-reference in Perl 6?

In Perl 5, I can do this:

my $d = [0 .. 9];
$#$d = 4;

In Perl 6, I get an error if I try this:

my $d = [0 .. 9];
$d.end = 4; # Cannot modify an immutable Int

This works, but it looks less beautiful than the Perl 5 way and may be expensive:

 $d.=splice(0, 5);
like image 816
sid_com Avatar asked Jan 18 '16 15:01

sid_com


2 Answers

There is a simple way:

my $d = [0..9];

$d[5..*] :delete;

That is problematic if the array is an infinite one.

$d.splice(5) also has the same problem.

Your best bet is likely to be $d = [ $d[^5] ] in the average case where you may not know anything about the array, and need a mutable Array.

If you don't need it to be mutable $d = $d[^5] which returns a List may be better.

like image 97
Brad Gilbert Avatar answered Sep 21 '22 17:09

Brad Gilbert


splice is probably the best choice here, but you can also shorten to five elements using the ^N range constructor shortcut (I call this the "up until" "operator" but I am sure there is a more correct name since it is a constructor of a Range):

> my $d = [ 0 .. 9 ];
> $d.elems
> 10
> $d = [ $d[^5] ]
[0 1 2 3 4]
> $d.elems
5
> $d
[0 1 2 3 4]

"The caret is ... a prefix operator for constructing numeric ranges starting from zero".
                                                                                  (From the Range documentation)

One can argue that perl6 is "perl-ish" in the sense it usually has an explicit version of some operation (using a kind of "predictable" syntax - a method, a routine, and :adverb, etc.) that is understandable if you are not familiar with the language, and then a shortcut-ish variant.

I'm not sure which approach (splice vs. the shortcut vs. using :delete as Brad Gilbert mentions) would have an advantage in speed or memory use. If you run:

perl6 --profile -e 'my $d = [ 0 .. 9 ]; $d=[ $d[^5] ]'
perl6 --profile -e 'my $d = [ 0 .. 9 ]; $d.=splice(0, 5);'

you can see a slight difference. The difference might be more significant if you compared with a real program and workload.

like image 26
G. Cito Avatar answered Sep 18 '22 17:09

G. Cito