A Look at Cartesian Products

A new post in my blog about Cartesian products.

Problem: You have a number of sets and you want all the combinations when choosing one element from each set.

In mathematics, these combinations are called the Cartesian products. They are also known as cross-products. In the database world, they are sometimes called cross-joins.


I wrote List::MapMulti specifically for iterating over Cartesian products...

use 5.010;
use List::MapMulti 'mapm';
my @A = qw( foo bar );
my @B = qw( 1 2 3 );
say for mapm { $_[0].$_[1] } \@A, \@B;

Toby, that looks cool, but it would be even cooler if you localize `$a` and `$b`. I don't have bitbucket account and no real desire to learn hg, so can I give you a patch right here?

On this line: https://bitbucket.org/tobyink/p5-list-mapmulti/src/7ff6d8128773c44c6b482b7432581e754b559dae/lib/List/MapMulti.pm?at=default#cl-53

if you did

local ($a, $b) = @values;

shouldn't that accomplish it? Cheers!

I hadn't considered this because mapm operates not just on 2 lists, but on N lists where N >= 1. But I suppose that N=2 is an especially common case.

The special $a and $b variables are package variables, not globals, so I think it's probably more like:

my $pkg = caller;
no strict 'refs';
local (${"$pkg\::a"), ${"$pkg\::b")) = @values;

Leave a comment

About shawnhcorey

user-pic Master Programmer, Perl Guru, & Avid Gamer