November 2012 Archives

Sequences, Sets, Bags, Functions

Groups of Items

A sequence is an ordered list of items, whose items aren't necessarily unique. Perl's arrays are sequences of a finite size:

my @sequence = qw/bar baz ban baz baz/;

A set, however, is an unordered collection of unique items. Perl provides native support for sets in the form of the keys of hashes:

my %set1 = map { $_ => undef } qw/foo bar baz/;
my %set2 = map { $_ => undef } qw/bar foo foo baz/; # Same as above
my %set3 = map { $_ =>…

De Morgan's laws in Perl

We've been simplifying some ugly code recently, and De Morgan's laws have come up more than once. A developer on the team complained the Wikipedia entry obscured - from a developer's perspective - the simplicity of these quite useful transformation rules, so, expressed in Perl:

Given $p and $q as truth values:

(! ( $p && $q ) ) == ( (! $p) || (! $q) )
(! ( $p || $q ) ) == ( (! $p) && (! $q) )

OR:

NOT( p AND q ) is equivalent to (NOT p) OR  (NOT q)
NOT( p OR  q ) is equivalent to (NOT p) AND (NOT q)

So for example, say you come…

About Peter Sergeant

user-pic I blog about Perl.