๐Ÿ“˜ Increasing sequences in Perl 6

๐Ÿ“˜ Increasing sequences in Raku

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

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

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