Skip to content

Instantly share code, notes, and snippets.

@gfldex
Created June 13, 2022 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfldex/e28992d7d85451ed669e7942f0b27e30 to your computer and use it in GitHub Desktop.
Save gfldex/e28992d7d85451ed669e7942f0b27e30 to your computer and use it in GitHub Desktop.
use v6.*;
class PredicateBatchIterator does Iterator {
class UnPrimed {}
has Iterator $.input is required;
has &.predicate is required;
has $.stashed is rw = UnPrimed;
submethod TWEAK { }
method pull-one {
my @a;
my $val;
my $prevval = UnPrimed;
return IterationEnd if $.stashed.WHICH === IterationEnd.WHICH;
if $.stashed !=== UnPrimed {
@a.push($.stashed);
$.stashed = UnPrimed;
}
loop {
$val := $.input.pull-one;
if $val =:= IterationEnd {
$.stashed = IterationEnd;
last;
}
if $prevval === UnPrimed {
@a.push: $val;
$prevval = $val;
next;
}
if &.predicate.($val) eqv &.predicate.($prevval) {
@a.push: $val;
$prevval = $val;
} else {
$.stashed = $val;
last;
}
}
@a
}
}
multi sub batch($_, &predicate) {
Seq.new: PredicateBatchIterator.new: input => .iterator, predicate => &predicate;
}
.say for [0..1000].&batch(*.chars);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment