[Issue 7128] Cartesian product of ranges

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Feb 9 03:17:33 PST 2013


http://d.puremagic.com/issues/show_bug.cgi?id=7128



--- Comment #17 from bearophile_hugs at eml.cc 2013-02-09 03:17:30 PST ---
(In reply to comment #16)
> Hmm, you're right. The cartesian power has the advantage that the output will
> be tuples of homogenous elements, so we can use arrays instead of tuples, which
> will allow runtime variation.

Right.

On the other hand if we do this, cartesianProduct() and cartesianPower() will
have different type (this means: they will be ranges that yield different class
of types, the first tuples, the second dynamic arrays). This requires people
that want to use such functions to remember this difference (a broken
symmetry). So this design decision has a little associated cost.

But in the end I prefer cartesianPower() to yield dynamic arrays because
dynamic arrays are more flexible, they offer both the size_t n to be a run-time
value, and dynamic arrays are more usable than tuples in D (I think tuples are
not ranges). Python itertools.cartesian doesn't have such problems because
Python is dynamically typed, so the items that itertools.cartesian are usable
like normal sequences (unlike D tuples).

If you use a cartesianProduct() to produce the data for the "Bulls and cows"
game you write something like:


auto d9 = "123456789"d.dup;
auto choices = cartesianProduct(d9, d9, d9, d9)
               .map!(t => [t.tupleof])()
               .filter!(a => a.sort().uniq().walkLength() == 4)()
               .array();


The map!(t => [t.tupleof])() is used to convert a tuple into a dynamic array,
so later on it you can perform more processing, with a filter() and an array().
D tuples don't play very well with ranges.

- - - - - - - - - - -

Maybe std.typecons.Tuple should define a handy std.typecons.Tuple.arrayof
attribute (that returns [this.tupleof]) when all the items of the tuple have
the same type.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list