Quick Tip 1: User-defined infinite sequences

Every day of the Learning Perl 6 Kickstarter campaign, I’ll present a quick tip about something I like in Perl 6. Let’s start with sequences.

We have simple sequences, like one digit to another. Here’s 0 to 9:

my $tenner := 0 ... 9;

Notice a few things here. I’ve used the infix binding operator, :=. It doesn’t assign a value, it makes the lefthand side the same as the righthand side.

The ... is the sequence operator, which we can use to produce lazy lists.

Lazy lists, you say? What if I wanted not just 0 to 9, but 0 to whatever number I felt like for as long as I wanted to run the program. I don’t know what that number might be, so I won’t specify it. I’ll just call it “whatever” with the *:

my $infinite := 0 ... *;

Perl 6 doesn’t compute this sequence. It knows that it starts at zero and keeps going until it reaches the end. That * is literally a Whatever object. When Perl 6 wants to know if it’s at the end, Whatever says no.

That could be a long, long list. But, the laziness takes care of that. Perl 6 doesn’t evaluate the next item until it needs it. This loop will go on forever:

for $infinite -> $next {
	say $next;

Big deal. We’ve had infinite loops forever (does anyone know who made the first one?). We can do this with loop:

loop ( my $i = 0; ; $i++ ) {
	say $i;

But, a loop is just a loop. It sits there all by itself. However, we can pass around a sequence, we can store it. We can so many other things with it. We can put it in a hash and choose the one we need later:

my %hash;

%hash<s> := 7 ... 10;
%hash<t> := 0 ...  3;
%hash<u> := 137 ...  *;

show( %hash{ time %% 2 ?? 't' !! 's' } );

sub show ( $s ) {
	.say for |$s;

Yep, we just stored an infinite number of values in a single hash value. I’ll have more on this in the next entry.


  1. Ada Localace made the first infinite loop. In the appendix to Luigi Menabrea book that she translated, she tried to implement the computation of Bernoulli numbers in such a buggy way that the program never terminated. This is assuming that neither Babbage nor Menabrea (who where programmers before Ada) made a similar mistake.

Leave a Reply

Your email address will not be published. Required fields are marked *