πŸ“˜ Checking odd and even numbers in Perl 6

Print the first ten odd numbers. Print the first ten even numbers.

Odd numbers are those that have a remainder after division by 2. This fact can be directly exploited in filtering the numbers and printing only those that match this definition.

.say if $_ % 2 for 1 .. 20;

To print even numbers, negate the condition by choosing another keyword:Β unless, instead ofΒ if:

.say unless $_ % 2 for 1 .. 20;

Numbers can be filtered using the grepbuilt-in function:

.say for grep {$_ % 2}, 1..20;

For the odd numbers, negate the condition by using the divisibility operator, which returnsΒ True when its first operand is divisible by the second with no remainder:

.say for grep {$_ %% 2}, 1..20;

Another interesting thing that Perl 6 offers is using a sequence. Show Perl the first elements of it, and it generates the rest:

my @odd = 1, 3 ... *;
say @odd[^10];

To print the even numbers, change the sample:

my @odd = 2, 4 ... *;
say @odd[^10];

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s