Skip to content

Commit

Permalink
Add R:It.AllButLast iterator
Browse files Browse the repository at this point in the history
Produce all values of a given iterator, except the last value.
For work that is underway refactoring the ... sequence generator
  • Loading branch information
lizmat committed Apr 1, 2020
1 parent 2b49d68 commit 77defa7
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/core.c/Rakudo/Iterator.pm6
Expand Up @@ -419,6 +419,29 @@ class Rakudo::Iterator {
#-------------------------------------------------------------------------------
# Methods that generate an Iterator (in alphabetical order)

# Create iterator that produces all values *except* the last of a given
# iterator. Returns an empty iterator if the given iterator did not
# produce any value
my class AllButLast does Iterator {
has $!iterator;
has $!value;

method !SET-SELF(\iterator) {
$!iterator := iterator;
nqp::eqaddr(($!value := iterator.pull-one),IterationEnd)
?? Rakudo::Iterator.Empty
!! self
}
method new(\iterator) { nqp::create(self)!SET-SELF(iterator) }
method pull-one() is raw {
my \this := $!value;
$!value := $!iterator.pull-one
unless nqp::eqaddr(this,IterationEnd);
this
}
}
method AllButLast(\iterator) { AllButLast.new(iterator) }

# Create iterator that produces all values *except* the last N values
# of a given iterator. Returns an empty iterator if the given iterator
# produced fewer than N values.
Expand Down Expand Up @@ -473,7 +496,9 @@ class Rakudo::Iterator {
}
}
method AllButLastNValues(\iterator, \n) {
AllButLastNValues.new(iterator,n)
n == 1
?? AllButLast.new(iterator)
!! AllButLastNValues.new(iterator,n)
}

# Return an iterator that will generate a pair with the value as the
Expand Down

0 comments on commit 77defa7

Please sign in to comment.