๐Ÿ“˜ Exclusion of two arrays in Perl 6

From the given two arrays, find the elements of the first array which do not appear in the second one.

Take two arbitrary arrays of integers:

my @a = 2, 5, 7, 8, 10;
my @b = 1, 3, 5, 7, 9;

The program should print 2, 8, and 10. Here is a possible solution:

my $b = Set(@b);
say grep * โŠ„$b, @a;

First, the array is converted to a set, which is later used to filter out the elements ofย @a for which there are no corresponding elements in the set.

A set in Perl 6 is a data type that contains a collection of unique elements. Theย $b set is created by calling the constructor that gets theย @b array as an initializer. The next interesting thing is how the program checks that the value is in the set. Theย grep function gets aย WhateverCode blockย *ย โŠ„$b, which is equivalent to the block with the default variable:ย {$_ย โŠ„$b}.

Finally, you can skip creating a separate set and use the array directly. The code looks more effective:

say grep * โŠ„@b, @a;

Theย โŠ„ operator returnsย True if its first operand, being treated as a set, is contained within the set on the right-hand side.ย The operator can be spelled purely in ASCII:

say grep * !(<) $b, @a;

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