Set operation like cartesian product

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Feb 28 15:01:48 PST 2013


On Thu, Feb 28, 2013 at 09:20:52PM +0100, Andrea Fontana wrote:
> On Thursday, 28 February 2013 at 18:23:04 UTC, H. S. Teoh wrote:
[...]
> >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
> 
> triangulaProduct2 for [0,1,2,3] and [0,1,2,3] doesn't give (0,0)
> (1,1) (2,2) (3,3)
> 
> :)

Ahhh, slight mistake there, it should be:

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

There, better now? ;-)

Also, if you only need products of finite ranges, it's possible to
rewrite it so that it produces items in a nicer order. The strange order
output by my examples are to cater for the infinite case.


T

-- 
Life would be easier if I had the source code. -- YHL


More information about the Digitalmars-d-learn mailing list