I think injectAccumulate is a bit of a mouthful and inject already
accumulates, but injectAll has a nice ring to it. I might create a PR
using that name.

Cheers, Paul.

On Wed, Mar 26, 2025 at 12:52 AM Mattias Reichel
<mattias.reic...@gmail.com> wrote:
>
> I think "injectMany" would be a good addition.
> It looks like a useful feature and it's important to keep up with the 
> features added in Java.
>
> Some silly brainstorming for method name:
> injectAccumulate (or injectAcc)
> injectAll
>
> /Mattias
>
> Den tis 25 mars 2025 kl 13:30 skrev Paul King <pa...@asert.com.au>:
>>
>> Hi folks,
>>
>> JDK24 brought with it the Gatherers API for enhanced stream processing.
>>
>> In traditional streams, we have the normal reduce operators, e.g.:
>>
>> var nums = 1..3
>> assert nums.stream().reduce('', (String string, number) -> string +
>> number) == '123'
>>
>> Groovy supports this for collections using "inject":
>>
>> assert nums.inject(''){ carry, next -> carry + next } == '123'
>>
>> But now there is also the prefix sum variant "scan", which I am told
>> has a myriad of uses, though I don't commonly use it myself. Note it
>> has the same reduce function as above:
>>
>> assert nums.stream()
>>     .gather(Gatherers.scan(() -> '', (string, number) -> string + number))
>>     .toList() == ['1', '12', '123']
>>
>> We can also emulate this for collections (with a little ugliness)
>> using the vanilla inject:
>>
>> assert nums.inject([]) { sum, next ->
>>     [*sum, "${sum.takeRight(1)[0] ?: ''}$next"]
>> } == ['1', '12', '123']
>>
>> I am wondering whether we could actually provide the same
>> functionality as scan above, something like this (name "injectMany"
>> currently but open to a better name):
>>
>> assert nums.injectMany(''){ carry, next -> carry + next } == ['1', '12', 
>> '123']
>>
>> It is only a minor change to the inject code, so not a huge technical
>> challenge, but what do folks think? Should we round out our collection
>> support to provide similar functionality to that available in streams?
>>
>> Regards,
>> Paul.

Reply via email to