I just started learning Scala, so please be patient :-)
I have a question about how reduceLeft behaves. Here an example:
List(1, 2, 3, 4, 5) reduceLeft (_ + _)
I wonder if the calculation can be done simultanously, e.g.:
first round:
second round:
third round:
At least that's what I would expect to happen if I just use the reduce function instead of reduceLeft. Or does reduceLeft really only does one reduction at a time?
((((1 + 2) + 3) + 4) + 5)
This would basically mean it can't be executed in parallel and one should always prefer reduce over reduceLeft/Right if possible?
The answer is yes, and it is very easy:
List(1, 2, 3, 4, 5).par.reduce (_ + _)
The par
method turns the list into a parallel collection. When you call reduce
on this parallel collection, it will be executed in parallel.
See the parallel collection documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With