7

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.

mscha
  • 6,509
  • 3
  • 24
  • 40
  • I would like to see an ```.isplice``` method (immutable splice) so you can go ``` @a.isplice($n,1)``` and it will return the result leaving @a unchanged. – librasteve Aug 02 '22 at 20:59
  • 1
    @p6steve, that's what I tried to suggest with `@b.spliced($n,1)`... – mscha Aug 09 '22 at 10:38

3 Answers3

8

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

Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
  • 1
    Thanks, @elizabeth, that will certainly do the trick. Still, a method `spliced` which returns the spliced array while leaving the original unchanged, would be a nice addition. – mscha Aug 09 '22 at 10:40
5

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

@a.grep: { $++ ≠ $n }
CIAvash
  • 716
  • 1
  • 6
  • 5
1

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.

raiph
  • 31,607
  • 3
  • 62
  • 111