πŸ“˜ Increasing sequences in Perl 6

Check if the given array contains increasing (or decreasing) numbers.

Given the list of numbers in an array, the task is to tell if all of them are sorted in ascending or descending order.

Take an array:

my @data = 3, 7, 19, 20, 34;

In Perl 6, reduction operators offer a very expressive and simple way to find the answer in one go:

say [<] @data;

With the values listed above, this program printsΒ True. Change the array to break the increasing sequence, and the program printsΒ False.

You will not be surprised to find out that to check whether the array is sorted in decreasing order, the code is as follows:

say [>] @data;

Using reduction operators is equivalent to inserting the main operator between the elements of the array, soΒ [<] @data is the same as the following chain of comparison operations:

say @data[0] < @data[1] < @data[2] < @data[3] < @data[4];

By the way, Perl 6’s ability to understand chained operations is very handy in theΒ if conditions, for example:

my $x = 15;
say 'ok' if 10 < $x < 20;

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