RFR: JDK-8319123 : Implementation of JEP-461: Stream Gatherers (Preview)
Viktor Klang
vklang at openjdk.org
Wed Nov 8 17:08:08 UTC 2023
On Wed, 8 Nov 2023 16:37:45 GMT, Tagir F. Valeev <tvaleev at openjdk.org> wrote:
>> TBH I don't think `foldRight` makes much sense for potentially unbounded structures such as Stream. In the case you need it, it might be better to export it to a List and then reversing it.
>
> Well, the unboundness argument does not hold, as it can be equally applied to any operation except the short-circuiting ones. Yes, this includes your `fold()`. The only difference is that `foldRight()` will fail with OutOfMemoryError while `fold()` will be stuck in the endless loop. Or probably also fail depending on the folder function (for example, if it's a string concatenation, like in the Javadoc example). You may not like the fact the `foldRight()` buffers the whole stream content, but we already have operations like this, namely `sorted()` and parallel ordered `distinct()`.
>
> I'm not convincing you to add `foldRight()` to the JDK. But if we don't have it, somebody will surely write it in third-party libraries. After all, this is what third-party libraries are for. In this case, simple name `fold()` can be confusing.
>
> Note that Haskell has separate foldl, foldr, scanl, scanr, so the order is always clear. Scala has `fold()` (which is like `reduce()` and can fold in any order), `foldLeft()` and `foldRight()`. Naming this method simply `fold()` sounds quite confusing. It should be either `foldLeft()` or `reduceLeft()` (even if we don't provide the -right versions)
The my argument around the unboundedness was semantical (starting from the end doesn't make semantical sense for something with no defined end). In this case it doesn't necessarily need to be an infinite stream for it to cause trouble, a large collection might be enough, since you need enough memory to reverse the order which means either making a full copy or having a (very) deep stack.
Having used "Left" and "Right"-named operations for a very long time, I am of the opinion that the "Left"-ones are the 98% use-case, so in this case I am inclined to be that it is going to be less confusing to developers to be "Left-biased" in the naming. I'm completely aware that I could be wrong here, yet with that said, I did give it a lot of thought before deciding.
My hope is that there will be a lot of `Gatherer`s created by Java developers so that they can use Streams for more use-cases, and be able to stay within Streams for as long as they need.
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/16420#discussion_r1386946766
More information about the core-libs-dev
mailing list