📘 Exclusion of two arrays in Perl 6

📘 Exclusion of two arrays in Raku

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


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