I'm trying to make an iterator, then build a sequence from it, but it doesn't act the way I think it should. What's up?
Here's my basic class:
class Foo {
has $.x = 0;
has $.max = 3;
method val() {
(++$!x > $!max) ?? () !! ($!x, "string $!x")
}
}
my $foo = Foo.new;
say $foo.val.perl for ^4;
# (1, "string 1")
# (2, "string 2")
# (3, "string 3")
# ()
It just iterates until max, then returns (), works the way I think it should.
Then I build an Iterator from that, just a single pull-one() method.
class Foo-Iterator does Iterator {
has Foo $.foo;
method pull-one() {
$!foo.val || IterationEnd
}
}
my $iter = Foo-Iterator.new(foo => Foo.new);
$iter.pull-one.perl.say for ^4;
# (1, "string 1")
# (2, "string 2")
# (3, "string 3")
# IterationEnd
It still acts the way I expect it to.
If I access it with a Seq, it still works fine:
.perl.say for Seq.new: Foo-Iterator.new(foo => Foo.new);
# (1, "string 1")
# (2, "string 2")
# (3, "string 3")
That is still what I expect to see, the same thing the Iterator returned.
Finally, I store the Seq in an @ variable and print the results of that:
my @seq = Seq.new: Foo-Iterator.new(foo => Foo.new);
.perl.say for @seq;
# $(4, "string 1")
# $(4, "string 2")
# $(4, "string 3")
What's up with that? It is seems to be using the later value of the variable rather than the value it had at the time of the pull-one call() (which the string forces to be a value). Does a Seq return it as a container rather than a value? Is this laziness in action, where it doesn't pull until requested so it gets a later value?
If I make val() return +$!x instead of returning $!x, it seems to grab the value and give me what I want, I'm just trying to understand the behavior I see.
$variable to store the Seq, then iterate withfor @$seq.