www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Confusing with chunkBy

reply Maksim <maximcorp mail.ru> writes:
Hello.
Why
chunkBy!((a,b) => a[1] == b[1])(
[
   [1,1],
   [1,2],
   [2,2],
   [2,1]
]);
returns a range with 3 subranges:
[
   [[1,1]],
   [[1,2], [2,2]],
   [[2,1]]
]
I thought it would returns a range with 2 subranges
[
   [[1,1], [2,1]],
   [[1,2],[2,2]]
]
It turns out that [1,1] and [2,1] are not grouped.

Thanks.
Feb 15 2021
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Monday, 15 February 2021 at 19:57:39 UTC, Maksim wrote:
 Hello.
 Why
The docs say it: "chunks an input range into subranges of equivalent adjacent elements." The key word there is "adjacent". and the docs follow up "Elements in the subranges will always appear in the same order they appear in the original range." What this means is it only looks at two side-by-side elements at a time, it doesn't scan ahead to find separated chunks. You may want to sort your data before you chunk it to ensure matching things are next to each other.
Feb 15 2021
parent reply Maksim <maximcorp mail.ru> writes:
On Monday, 15 February 2021 at 20:08:45 UTC, Adam D. Ruppe wrote:
 On Monday, 15 February 2021 at 19:57:39 UTC, Maksim wrote:
 Hello.
 Why
The docs say it: "chunks an input range into subranges of equivalent adjacent elements." The key word there is "adjacent".
Thanks for answer, Adam. I lost the key word "adjacent".
Feb 15 2021
parent Adam D. Ruppe <destructionator gmail.com> writes:
On Monday, 15 February 2021 at 20:51:53 UTC, Maksim wrote:
 Thanks for answer, Adam. I lost the key word "adjacent".
yeah, you aren't the only one, I think the docs should call it more more illustratively with an example or something too. The reason why it is designed this way is just to get minimum cost - this is the simplest thing that can be useful so you don't pay for a sort you don't need. But then if you do need it, gotta do it yourself. (And sort requires an array to put the results into, so if you pass it an array it will just mutate the existing one, and if it isn't passed an array, again it does the bare minimum work it can to be useful, so it may fail compile and you must allocate one yourself. Just a couple other things to keep your eyes open for as you explore the library.)
Feb 15 2021