nus-cs2030 / 2021-s1

27 stars 48 forks source link

reduce() for parallel streaming #545

Closed limeugene closed 3 years ago

limeugene commented 3 years ago

Hi, I am trying to reverse a String in a parallel stream, and I don't understand why the following code works. I am under the impression that the combiner and accumulator needs to be associative, but in the following code, we are concatenating strings together, which is not associative thus undeterministic in a parallel stream? Would appreciate if anyone knows why the code works. thanks :)

image

kaiyang96 commented 3 years ago

Hello, I do believe that concatenating of Strings is associative. Where for characters x, y, z: ((x, y), z) = xyz = (x, (y, z)). Or for this reversing case: ((x, y), z) = zyx = (x, (y, z)). You may have it mixed up with the commutative property which is x + y = y + x, which fails for String concatenating.

limeugene commented 3 years ago

@kaiyang96 ahh I see thanks so much for the reply!!