I am reading through perl6intro on lazy lists and it leaves me confused about certain things.
Take this example:
sub foo($x) {
$x**2
}
my $alist = (1,2, &foo ... ^ * > 100);
will give me (1 2 4 16 256)
, it will square the same number until it exceeds 100. I want this to give me (1 4 9 16 25 .. )
, so instead of squaring the same number, to advance a number x
by 1 (or another given "step"), foo x
, and so on.
Is it possible to achieve this in this specific case?
Another question I have on lazy lists is the following: In Haskell, there is a takeWhile function, does something similar exist in Perl6?
Here is how you could write a Perl 6 equivalent of Haskell's
takewhile
.I should probably also show an implementation of
dropwhile
.These are only just-get-it-working examples.
It could be argued that these are worth adding as methods to lists/iterables.
You could (but probably shouldn't) implement these with the sequence generator syntax.
If they were added to Perl 6/Rakudo, they would likely be implemented with Iterator classes.
( I might just go and add them. )
A direct implementation of what you are asking for is something like:
Which can be done with state variables:
And a state variable that isn't used outside of declaring it doesn't need a name.
( A scalar variable starts out as an undefined Any, which becomes 0 in a numeric context )
If you need to initialize the anonymous state variable, you can use the defined-or operator
//
combined with the equal meta-operator=
.In some simple cases you don't have to tell the sequence generator how to calculate the next values.
In such cases the ending condition can also be simplified.
The only other time you can safely simplify the ending condition is if you know that it will stop on the value.