πŸ“˜ Finding the first odd number using Perl 6

Find the first odd number in a list of integers.

The task is to find the first odd number in a given list of odd and even numbers. A good candidate is the firstroutine, which searches for the leftmost value (see, for example, Task 58, Is an element in a list?). Now, we can pass an anonymous code block to it to calculate the predicate.

my @nums = (2, 4, 18, 9, 16, 7, 10);
my $first = @nums.first: * % 2;
say $first; # Prints 9

Colon syntax is used here to pass arguments to methods. The same call may be written in the traditional style with parentheses:

my $first = @nums.first(* % 2);

The construction with a star (which is calledΒ Whatever) creates a code block with one argument, equivalent toΒ {$a % 2}, that returnsΒ True when the number is odd. The same code can be rewritten less efficiently with aΒ grep:

my @odd = grep {$_ % 2}, @nums;
say @odd[0]; # Prints 9

Let us try another method by matching the value against a regex that tests whether the last digit of a number is odd:

@nums ~~ /(\d*<[13579]>$)/;
say $/[0];

The whole array is matched against the regex, and the first captured value is printed.

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