routine splice
Documentation for routine splice
assembled from the following types:
role Buf
From Buf
(Buf) method splice
method splice( Buf:D: $start = 0, $elems?, *@replacement --> Buf)
Substitutes elements of the buffer by other elements
$bú.splice: 0, 3, <3 2 1>; say $bú.raku; # OUTPUT: «Buf.new(3,2,1,2,3,5,8,13,21,34,55,89)»
class Array
From Array
(Array) routine splice
Defined as:
multi sub splice(@list, $start = 0, $elems?, *@replacement --> Array) multi method splice(Array:D: $start = 0, $elems?, *@replacement --> Array)
Deletes $elems
elements starting from index $start
from the Array
, returns them and replaces them by @replacement
. If $elems
is omitted or is larger than the number of elements starting from $start
, all the elements starting from index $start
are deleted. If both $start
and $elems
are omitted, all elements are deleted from the Array
and returned.
Each of $start
and $elems
can be specified as a Whatever or as a Callable that returns an Int
-compatible value.
A Whatever
$start
uses the number of elements of @list
(or invocant). A Callable
$start
is called with one argument—the number of elements in @list
(or self
) —-and its return value is used as $start
.
A Whatever
$elems
deletes from $start
to end of @list
(or self
) (same as no $elems
). A Callable
$elems
is called with just one argument—the number of elements in @list
minus the value of $start
—and its return value is used the value of $elems
.
Example:
my @foo = <a b c d e f g>; say @foo.splice(2, 3, <M N O P>); # OUTPUT: «[c d e]» say @foo; # OUTPUT: «[a b M N O P f g]»
It can be used to extend an array by simply splicing in more elements than the current size (since version 6.d)
my @foo = <a b c d e f g>; say @foo.splice(6, 4, <M N O P>); # OUTPUT: «[g]» say @foo; # OUTPUT: «[a b c d e f M N O P]»
The following equivalences hold (assuming that @a.elems ≥ $i
):
@a.push($x, $y) @a.splice: * , *, $x, $y @a.pop @a.splice: *-1, @a.shift @a.splice: 0 , 1, @a.unshift($x, $y) @a.splice: 0 , 0, $x, $y @a[$i] = $y @a.splice: $i , 1, $y,
As mentioned above, a Whatever
or Callable
object can be provided for both the $start
and $elems
parameters. For example, we could use either of them to remove the second to last element from an array provided it's large enough to have one:
my @foo = <a b c d e f g>; say @foo.splice: *-2, *-1; # OUTPUT: «[f]» say @foo; # OUTPUT: «[a b c d e g]» my &start = -> $n { $n - 2 }; my &elems-num = -> $m { $m - 1 }; say @foo.splice: &start, &elems-num; # OUTPUT: «[e]» say @foo; # OUTPUT: «[a b c d g]»