[Purdue-pm] Perl 6 sets

Mark Senn mark at purdue.edu
Thu Mar 21 19:06:15 PDT 2019


Purdue Perl Mongers,

Thought you might be interested in the following Perl 6 program.  If
your problem domain is sets, Perl 6 supports those very naturally,
including the Unicode math symbols for union, intersection, and set
difference.  There are non-Unicode versions of the symbols if you don't
like Unicode.    -mark



# Read files 'a', 'b', 'c', and 'd' and print the unique lines that
# are in 'a' or 'b', and aren't in both 'c' and 'd'.

use v6;

# Define a sub so we don't need to write
#     my $a = 'a'.IO.lines.Set;
#     my $b = 'b'.IO.lines.Set;
#     [...]
# Read all lines in $filename, make a set, and return the set.
sub readset($filename) { return $filename.IO.lines.Set; }

my $a = readset 'a';
my $b = readset 'b';
my $c = readset 'c';
my $d = readset 'd';

# SYMBOL    DESCRIPTION       UNICODE CODEPOINT
# ∩         intersection      U+2229
# ∖         set difference    U+2216
# ∪         union             U+222A            
#
# Using my 'a', 'b', 'c', and 'd' test files gives
# $a   is   (a b c)
# $b   is   (c d e)
# $c   is   (c d)
# $d   is   (c e)
# ($a ∪ $b)                is    (a b c d e)
# ($c ∩ $d)                is    (c)
# ($a ∪ $b) ∖ ($c ∩ $d)    is    (a b d e)
(($a ∪ $b) ∖ ($c ∩ $d)).keys.sort.say;

# Or, if you don't like to use Unicode characters:
(($a (|) $b) (-) ($c (&) $d)).keys.sort.say;


More information about the Purdue-pm mailing list