Seq::Manual::FromSub
Seq::Manual::FromSub
A deeper explanation how Seq->from_sub
works.
THE PROBLEM
You could write the following in Perl
|
|
but it would be a bad idea. Perls range operator is non-lazy. When
you call the above code perl will create an array with 10 Mio numbers
and then pass that 10 Mio numbers to Seq->wrap
.
This is not only time-consuming, it will also use a lot of memory. Maybe with a bigger number your program or your computer could even crash with out of memory.
This is the reason why you should use
|
|
instead. It returns a sequence but nothing is computed yet. It only starts computing values when the sequence is request for values. And even then it will still only compute as much as needed, or keep those values in memory that are needed.
Seq->range
is already provided by this module. But what would be the case
if not?
Then you could create your own range function using Seq->from_sub
range
Here is how to implement your own range
function.
|
|
The pattern you do with from_sub
is always the same. It is.
|
|
You can use it directly to create a special sequence as needed, or return it from a function. So you have a reusable CONSTRUCTOR for creating your own sequences.
Maybe the most simple sequence would be an infinity sequence always returning the same value forever.
|
|
You could do
|
|
to just get an array [1,1,1,1,1,1,1,1,1,1]
. Don’t forget the take(10)
otherwise the sequence will run forever until all your computer memory
is exhausted and your program or computer crashes.
But you could do
|
|
and it will run in an endless-loop, forever printing dots until you abort the program.