Raku: a language that counts to infinity (Part 2)
In this part, let's look at infinite sequences from another angle: let's start collecting the values. First of all, Raku has a pair of built-in routines gather and take . They are useful when you need to collect data that's computed along the way. For example: my @data = gather { for ^50 { my $value = 100.rand.Int; take $value if 45 < $value < 55; } } say @data ; The program prints a few random numbers between 45 and 55 (or none when unlucky). You don't know upfront how many numbers it will pick, but at least there's some limit: the loop body runs only 50 times, and the random numbers are less than 100. So, it's time to introduce some infinity into the code. The next program scans the number, but does not explicitly say how many of them the user will use later. The second line, for example, demands the first five items, and that's when the real computation happens: my $data = gather for 1 .. ∞ { take $_ if 45 < $_ < 55 } say $data[^5]; # (46 47 48 49 50) Surprisingly, working with infinities makes the code clearer for the reader. You just describe what to do with data, but omit the length. The next snippet literally says “Convert the numbers to their squares”. You apply this rule to the infinite (but lazy) range 1 .. ∞ , and only then you take the first five elements. say (gather for 1 .. ∞ { take $_ × $_ }).head(5); Once again, note that you first apply the action to an infinite sequence, and only then cut it to the size you need. Not vice versa (of course you can if you know when to stop; but sometimes you need the condition on the results rather than on the source). The program prints: (1 4 9 16 25) A similar approach is demonstrated in the next two lines: say ([\+] 1 .. ∞)[^10]; say ([\*] 1 .. ∞)[^7]; Wait, how? Add up or multiply all the integer numbers, and then take the first few elements of one of the triangle metaoperator's results?! Yes, no problem. A couple of triangle metaoperators are only used to compute the values for the first few items, not for the