Skip to content

Instantly share code, notes, and snippets.

@lizmat
Last active June 16, 2017 21:26
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 lizmat/063358317dc17a87d32f6d01de1c2687 to your computer and use it in GitHub Desktop.
Save lizmat/063358317dc17a87d32f6d01de1c2687 to your computer and use it in GitHub Desktop.
.condense
use MONKEY;
augment class List {
method condense(List:D:) {
Seq.new( class :: does Iterator {
has $.iterator;
has $!first;
has $!last;
method pull-one() {
if $!iterator {
if (my $pulled := $!iterator.pull-one) =:= IterationEnd {
$!iterator = Nil;
$!first.defined
?? $!first == $!last
?? $!last
!! Range.new($!first,$!last)
!! IterationEnd
}
elsif $pulled ~~ Int:D {
if $!first.defined {
if $pulled == $!last + 1 {
++$!last;
++$!last
while !(($pulled := $!iterator.pull-one) =:= IterationEnd)
&& $pulled ~~ Int:D
&& $pulled == $!last + 1;
}
if $pulled =:= IterationEnd || $pulled ~~ Int:D {
my $value = $!first == $!last
?? $!last
!! Range.new($!first,$!last);
$pulled =:= IterationEnd
?? ($!iterator = Nil)
!! ($!first = $!last = $pulled);
$value
}
else {
die "Cannot handle $pulled.perl()"
}
}
else {
$!first = $!last = $pulled;
self.pull-one
}
}
else {
die "Cannot handle $pulled.perl()"
}
}
else {
IterationEnd
}
}
method is-lazy() { $!iterator.is-lazy }
}.new(iterator => self.iterator))
}
}
#dd (1,2,3,7,9,10,11,12).condense;
dd ^1000000 .list.condense;
#dd ().condense;
#dd (Int,).condense;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment