[WORK] groupBy is in! Next: aggregate

via Digitalmars-d digitalmars-d at puremagic.com
Mon Jan 26 14:29:21 PST 2015


On Monday, 26 January 2015 at 18:31:05 UTC, Andrei Alexandrescu 
wrote:
>
> So the key (ahem) here is to make groupBy with unary predicate 
> different from groupBy with binary predicate. The former 
> returns the tuple, the latter is unchanged. Makes sense?

The current implementation has a certain beauty and does not lend 
itself easily to a split in two different versions. Also, the 
additional key return value might be unnecessary and unexpected 
in many cases.

You can easily build the extended groupBy function out of the 
current one, if you only calculate the predicate beforehand. If 
the predicate is expensive, this might be sensible anyway.

auto groupByStar(alias pred, Range)(Range r)
{
   return r.map!(pred, "a")
	.groupBy!(a => a[0])
	.map!(inner => tuple(inner.front[0], inner.map!"a[1]"))
	;
}

void main()
{
   auto a = iota(10);
   foreach (r; a.groupByStar!"a/3") {
	writeln(r[0], " ", r[1]);
   }
}

I do not know if this solution is any better. The above might be 
a terrible idea.

Note: I failed to compile `r.groupBy!"a[0]"` with

iteration.d(1648): Error: function expected before (), not "a[0]" 
of type string


More information about the Digitalmars-d mailing list