What's an elegant way to return a list without the nth element?

Viewed 149

What is an elegant and efficient way to return a list without the nth element? I'm now using something like:

my @b = @a;
@b.splice($n,1);
return @b;

but that's not very elegant, and probably not efficient either.

(Something like return @b.spliced($n,1) would be nicer, but that doesn't work.)

return flat @a[0..^$n,$n^..*]

isn't much better.

3 Answers

I don't know of any other way other than the ones you described.

I have been thinking about expanding the .skip method to multiple parameters, which would allow for @b.skip($n,1).

EDIT: this is now a Pull Request

EDIT: this has now been merged and will be in the 2022.08 release

I don't know about elegant or efficient, but another solution is this:

@a.grep: { $++ ≠ $n }

Not built in, assumes exdices are already in sorted order and don't overlap, may not be optimizable, not type checked, but at least "sugared" -- though whether it's natural or artificial, whether it's healthy or rots your gut, is a matter of taste:

multi postcircumfix:<[- ]> (|args) { remove |args }

sub remove( @arg is copy, +@exdices){
  for @exdices .reverse {
    when Int   { @arg .splice: $_,   1 }
    when Range { @arg .splice: .min, +$_ }
  }
  @arg
}

Use like this for example:

say (0,1,2,3,4,5)[- 1..2, 4]; # [0 3 5]

This "solution" is an array variant of my answer to "Remove some characters from a string by index", with the caveats mentioned in both this answer and the earlier one.

Related