rakuvariadic

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


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?


Solution

  • 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.