Set operation like cartesian product

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Feb 28 10:21:06 PST 2013


On Thu, Feb 28, 2013 at 04:31:59PM +0100, Andrea Fontana wrote:
> I see cartesianProduct in std.algorithm. I read:
> 
> auto N = sequence!"n"(0); // the range of natural numbers
> auto N2 = cartesianProduct(N, N); // the range of all pairs of
> natural numbers
> 
> So it gives (0,0) (0,1) (1,0) ... and so on.
> 
> Is there a way to generate only tuple:
> 
> a[0] > a[1] (0,1) (0,2) ... (1,2) (1,3) .. (2,3) (2,4)
[...]

auto triangularProduct(R1,R2)(R1 r1, R2 r2)
	if (isForwardRange!R1)
{
	return map!(function(a) => zip(take(a[1].save, a[0]), repeat(a[2])))(
			zip(sequence!"n"(0), repeat(r1.save), r2)
		)
		.joiner();
}

Both ranges can be infinite, only the first one needs to be a forward
range.


> a[0] >= a[1] (0,0) (0,1) (0,2) ... (1,1) (1,2) (1,3) .. (2,2) (2,3)
> (2,4)
[...]

auto triangularProduct2(R1,R2)(R1 r1, R2 r2)
	if (isForwardRange!R1)
{
	return map!(function(a) => zip(take(a[1].save, a[0]), repeat(a[2])))(
			zip(sequence!"n"(1), repeat(r1.save), r2)
		)
		.joiner();
}

As above, both ranges can be infinite, only the first one needs to be a
forward range.

Hope this helps. ;-)


T

-- 
Gone Chopin. Bach in a minuet.


More information about the Digitalmars-d-learn mailing list