Philip R Brenan >
Math-Cartesian-Product-1.008 >
Math::Cartesian::Product

Module Version: 1.008
Math::Cartesian::Product - Generate the Cartesian product of zero or more lists.

use Math::Cartesian::Product; cartesian {print "@_\n"} [qw(a b c)], [1..2]; # a 1 # a 2 # b 1 # b 2 # c 1 # c 2 cartesian {print "@_\n"} ([0..1]) x 8; # 0 0 0 0 0 0 0 0 # 0 0 0 0 0 0 0 1 # 0 0 0 0 0 0 1 0 # ... # 1 1 1 1 1 1 1 0 # 1 1 1 1 1 1 1 1

Generate the Cartesian product of zero or more lists.

Given two lists, say: [a,b] and [1,2,3], the Cartesian product is the set of all ordered pairs:

(a,1), (a,2), (a,3), (b,1), (b,2), (b,3)

which select their first element from all the possibilities listed in the first list, and select their second element from all the possibilities in the second list.

The idea can be generalized to n-tuples selected from n lists where all the elements of the first list are combined with all the elements of the second list, the results of which are then combined with all the member of the third list and so on over all the input lists.

It should be noted that Cartesian product of one or more lists where one or more of the lists are empty (representing the empty set) is the empty set and thus has zero members; and that the Cartesian product of zero lists is a set with exactly one member, namely the empty set.

`cartesian()`

takes the following parameters:

1. A block of code to process each n-tuple. this code should return true if the current n-tuple should be included in the returned value of the `cartesian()`

function, otherwise false.

2. Zero or more lists.

`cartesian()`

returns an array of references to all the n-tuples selected by the code block supplied as parameter 1.

`cartesian()`

croaks if you try to form the Cartesian product of something other than lists of things.

The cartesian product of lists A,B,C is associative, that is:

(A X B) X C = A X (B X C)

`cartesian()`

respects associativity by allowing you to include a Cartesian product produced by an earlier call to `cartesian()`

in the set of lists whose Cartesian product is to be formed, at the cost of a performance penalty if this option is chosen.

use Math::Cartesian::Product; my $a = [qw(a b)]; my $b = [cartesian {1} $a, $a]; cartesian {print "@_\n"} $b, $b; # a a a a # a a a b # a a b a # ...

`cartesian()`

is easy to use and fast. It is written in 100% Pure Perl.

The `cartesian()`

function is exported.

Standard Module::Build process for building and installing modules:

perl Build.PL ./Build ./Build test ./Build install

Or, if you're on a platform (like DOS or Windows) that doesn't require the "./" notation, you can do this:

perl Build.PL Build Build test Build install

PhilipRBrenan@appaapps.com

With much help and good natured advice from Philipp Rumpf to whom I am greatly indebted.

Copyright (c) 2009 Philip R Brenan.

This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.

syntax highlighting: