Skip to content

Commit

Permalink
Move the Lazy iterator class to Rakudo::Iterator
Browse files Browse the repository at this point in the history
To make it more in line with other iterators that live there.  And
more generally available, should that be needed.  And add some comments.
  • Loading branch information
lizmat committed Dec 25, 2019
1 parent 971174f commit e8a9e07
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 28 deletions.
29 changes: 1 addition & 28 deletions src/core.c/Iterable.pm6
Expand Up @@ -80,38 +80,11 @@ my role Iterable {

method lazy-if($flag) { $flag ?? self.lazy !! self }

my class Lazy does Iterator {
has $!iterable;
has $!iterator;

method new(\iterable) {
my \iter := nqp::create(self);
nqp::bindattr(iter,self,'$!iterable',iterable);
nqp::bindattr(iter,self,'$!iterator',nqp::null);
iter
}

method pull-one() is raw {
nqp::ifnull(
$!iterator,
$!iterator := $!iterable.iterator
).pull-one
}

method push-exactly(\target, int $n) {
nqp::ifnull(
$!iterator,
$!iterator := $!iterable.iterator
).push-exactly(target, $n);
}

method is-lazy(--> True) { }
}
method lazy() {
# Return a Seq with an iterator wrapping this Iterable, claiming to
# be lazy, and implicitly preventing working ahead (by hiding any
# push-at-least-n of the source iterator).
Seq.new(Lazy.new(self))
Seq.new(Rakudo::Iterator.Lazy(self))
}

method hyper(Int(Cool) :$batch = 64, Int(Cool) :$degree = 4) {
Expand Down
33 changes: 33 additions & 0 deletions src/core.c/Rakudo/Iterator.pm6
Expand Up @@ -2155,6 +2155,39 @@ class Rakudo::Iterator {
)
}

# Return an iterator that is always lazy, by wrapping it inside another
# iterator that indicates to be lazy. Does not actually call the
# iterator until it is really necessary, preventing any unnecessary
# work or external resource usage.
my class Lazy does Iterator {
has $!iterable;
has $!iterator;

method new(\iterable) {
my \iter := nqp::create(self);
nqp::bindattr(iter,self,'$!iterable',iterable);
nqp::bindattr(iter,self,'$!iterator',nqp::null);
iter
}

method pull-one() is raw {
nqp::ifnull(
$!iterator,
$!iterator := $!iterable.iterator
).pull-one
}

method push-exactly(\target, int $n) {
nqp::ifnull(
$!iterator,
$!iterator := $!iterable.iterator
).push-exactly(target, $n);
}

method is-lazy(--> True) { }
}
method Lazy(\iterable) { Lazy.new(iterable) }

# Return an iterator given a List and an iterator that generates
# an IterationBuffer of indexes for each pull. Each value is
# is a List with the mapped elements.
Expand Down

0 comments on commit e8a9e07

Please sign in to comment.