📘 Printing a list of prime numbers using Perl 6

📘 Printing a list of prime numbers using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.

Print thelist of the first ten prime numbers.

In Task 27, Prime numbers, we’ve seen how to check if the given number is prime. To print the list of the first ten numbers, organize a lazy list.The code is quite compact and Perlish by nature:

my @numbers = grep {.is-prime}, 1..*;
say @numbers[^10];

The first line has to be read from right to left. The lazy list 1..* is filtered with the grep function, and another lazy list resides in the @numbers variable.

Then, the first ten elements are taken and printed:

(2 3 5 7 11 13 17 19 23 29)

In Perl 6, it is possible to use the colon to pass arguments to functions. The above-shown code can be rewritten differently:

my @numbers = (1..*).grep: *.is-prime;
say @numbers[^10];

Notice that the two usages of * mean different things here. The range of 1..* is replaceable with an open-end range ^∞ or ^Inf.

my @numbers = (^Inf).grep: *.is-prime;
say @numbers[^10];

Finally, make a selection of the first ten elements directly:

say ((^∞).grep: *.is-prime)[^10];

Leave a Reply

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