Ranges/algorithms for aggregation
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Mar 21 09:52:02 PDT 2014
On Fri, Mar 21, 2014 at 04:10:12PM +0000, Justin Whear wrote:
[...]
> This pull request[1] for groupBy has been hanging around for a year
> now, driving me to copy-and-paste the implementation into a couple of
> my projects. Using it, you could do this:
>
> auto tuples = ... // get your list of (B, foo), (B, bar), etc.
> auto output = tuples.sort!`a[0] < b[0]`
> .groupBy!`a[0] == b[0]`;
> // output is a range of:
> // [
> // [(A, begga)],
> // [(B, foo), (B, bar), (B, big)],
> // [(C, ble)]
> // ]
>
> The advantage being that output isn't an array at all but a lazy range
> of lazy ranges.
>
> 1 https://github.com/D-Programming-Language/phobos/pull/1186
Be aware, though, that groupBy only compares *adjacent* elements for
equivalence; it does not sort the input. So if your input has equivalent
elements interspersed with non-equivalent elements, you will have the
equivalent elements split into multiple runs in the output.
Example:
auto data = [
tuple(1, "a")
tuple(1, "b")
tuple(2, "c")
tuple(1, "d")
];
writeln(data.groupBy!((a,b) => a[0] == b[0]));
Will output:
[[tuple(1, "a"), tuple(1, "b")], [tuple(2, "c")], [tuple(1, "d")]]
Which may not be what the OP wants.
T
--
Unix was not designed to stop people from doing stupid things, because that would also stop them from doing clever things. -- Doug Gwyn
More information about the Digitalmars-d-learn
mailing list