MoreLINQ icon indicating copy to clipboard operation
MoreLINQ copied to clipboard

Multidimensional Cartesian

Open emphasis87 opened this issue 8 years ago • 7 comments

Hi,

is there a better way to write a multidimensional cartesian then this?

var argList = new List<IEnumerable<Type>>();
var args = argList.Aggregate(new List<List<Type>>(), (acc, arg) =>
{
	if (acc.IsEmpty())
		acc.AddRange(arg.Select(x => new[] { x }.ToList()));
	else
		acc.Cartesian(arg, (a, b) =>
		{
			a.Add(b);
			return a;
		}).Consume();
	return acc;
});

I didn't test it, but surely there is a better way to combine multiple sequences?

If not, would you consider extending Cartesian with overloads for multiple sequences?

emphasis87 avatar Aug 05 '17 11:08 emphasis87

Try this.

ooraini avatar Oct 22 '17 00:10 ooraini

I'm willing to take this up. I imagine we could implement it in T4 like we do for Fold.

Arithmomaniac avatar May 15 '18 17:05 Arithmomaniac

@Arithmomaniac Thanks for volunteering.

I think what's sought here is a Cartesian product implementation over a dynamic list of sequences so how do you see that following the footsteps of Fold?

atifaziz avatar May 15 '18 20:05 atifaziz

That's what @emphasis87 sought, but I think like Fold would be better so that you could have source sequences of different types.

Arithmomaniac avatar May 15 '18 20:05 Arithmomaniac

would be better so that you could have source sequences of different types.

I see, but then I think that would make it a different issue altogether. Nevertheless, how would that be any different than chaining nested fromin clauses like below (where x, y and z can be different types)?

var result =
    from x in xs
    from y in ys
    from z in zs
    select (x, y, z);

In fact, that's all Cartesian is today and I'm not so sure it should have ever been part of MoreLINQ in the first place because it doesn't add much more value on top what's already natively and simply expressible in LINQ.

atifaziz avatar May 15 '18 20:05 atifaziz

Maybe just rename this one to be more noncommital at this point?

Anyways, the from syntax is a) only possible in query syntax, but more importantly b) has a quadratic enumeration problem, because it is compiled as a chain of SelectManys (as you can see on SharpLab).

Arithmomaniac avatar May 15 '18 20:05 Arithmomaniac

Anyways, the from syntax is a) only possible in query syntax, but more importantly b) has a quadratic enumeration problem, because it is compiled as a chain of SelectManys

True on both accounts, and in fact, once #488 has been addressed, it'll be sufficiently different from SelectMany.

I still think it should be addressed as a new issue because it can be confusing for a future visitor to see the opening comment asking for a Cartesian product of homogeneous sequences and the resolution being one addressing heterogeneous ones.

atifaziz avatar May 17 '18 14:05 atifaziz