darren chamberlain wrote:
> Since first and last would be defined as:
>
> 'first' => sub {
> my $list = shift;
> return $list->[0] unless @_;
> return list_splice_vmeth($list, 0, $_[0]);
> }
> 'last' => sub {
> my $list = shift;
> return $list->[$#$list] unless @_;
> return list_splice_vmeth($list, -$_[0], $_[0]);
> }
Yep, but we can slice it direct:
'first' => sub {
my $list = shift;
return $list->[0] unless @_;
return [ @$list[0..$_[0]-1] ];
},
'last' => sub {
my $list = shift;
return $list->[-1] unless @_;
return [ @$list[-$_[0]..-1] ];
},
I'm not fussed about supporting negative values for first() and last().
Better to keep it simple, I think.
> > Slice
> > -----
> >
> > Right, I think that slice should return a copy of the list, and return the
> > bits mentioned.
> >
> > [% newlist = mylist.slice(2,3) %]
> > -- returns 3rd, 4th, and 5th as new list
Yes it should return a copy of the elements of the list, but I think
the parameters should be (start, end) rather than (start, offset).
Then it's more like Perl, even if it is less like splice():
@items = @list[$from..$tom];
[% items = list.slice(from, to) %]
How about this:
'slice' => sub {
my ($list, $from, $to) = @_;
$from ||= 0;
$to = $#$list unless defined $to;
return [ @$list[$from..$to] ];
},
Here's a test:
-- test --
-- name slice --
[% primes = [ 2, 3, 5, 7, 11, 13 ] -%]
[% primes.slice(0, 2).join(', ') +%]
[% primes.slice(-2, -1).join(', ') +%]
[% primes.slice(3).join(', ') +%]
[% primes.slice.join(', ') +%]
--expect --
2, 3, 5
11, 13
7, 11, 13
2, 3, 5, 7, 11, 13
> Language design is hard.
But fun :-)
A