Created
June 13, 2022 20:55
-
-
Save gfldex/e28992d7d85451ed669e7942f0b27e30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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