Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent in Perl 6 to star expressions in Python?

Tags:

variadic

raku

In Python 3, suppose you run a course and decide at the end of the semester that you’re going to drop the first and last homework grades, and only average the rest of them:

def drop_first_last(grades):
    first, *middle, last = grades 
    return avg(middle)

print drop_first_last([100,68,67,66,23]);

In Perl 6:

sub drop_first_last(@grades) {
    my ($first, *@middle, $last) = @grades;
    return avg(@middle);
}

say drop_first_last(100,68,67,66,23);

Leads to the error "Cannot put required parameter $last after variadic parameters".

So, what's the equivalent express in Perl 6 as star expressions in Python?

like image 660
chenyf Avatar asked May 03 '18 15:05

chenyf


2 Answers

sub drop_first_last(Seq() \seq, $n = 1) { seq.skip($n).head(*-$n) };
say drop_first_last( 1..10 );     # (2 3 4 5 6 7 8 9)
say drop_first_last( 1..10, 2 );  # (3 4 5 6 7 8)

The way it works: convert whatever the first argument is to a Seq, then skip $n elements, and then keep all except the last $n elements.

like image 194
Elizabeth Mattijsen Avatar answered Jan 01 '23 21:01

Elizabeth Mattijsen


Perl5:

sub drop_first_last { avg( @_[ 1 .. $#_-1 ] ) }     #this
sub drop_first_last { shift;pop;avg@_ }             #or this

Perl6:

sub drop_first_last { avg( @_[ 1 .. @_.end-1 ] ) }
like image 34
Kjetil S. Avatar answered Jan 01 '23 22:01

Kjetil S.