📘 Finding minimum and maximum using Perl 6

Find the minimum and the maximum numbers in the given list of integers.

Finding the minimum and maximum elements of arrays is extremely easy in Perl 6. For iterable objects, the two methods, min and max, are defined.

my @list = 7, 6, 12, 3, 4, 10, 2, 5, 15, 6, 7, 8, 9, 3;

say @list.min;
say @list.max;

For the list in the example, this program prints two numbers:

2
15

The min and max routines can be used as binary operators, in which case they return the smaller or the bigger number:

say 7 min 8; # Prints 7
say 7 max 8; # Prints 8

Operators can be chained like this:

say 7 min 5 min 8; # Prints 5
say 7 max 5 max 8; # Prints 8

This can be expressed with the help of a reduction meta-operator […]:

say [min] 7, 9, 5; # Prints 5
say [max] 7, 9, 4; # Prints 9

Lists are also accepted, for example: say [min] @list.

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