Course of Raku / Functional, concurrent, reactive, and web programming / Concurrent programming / Hyper and race 🆕 / Exercises / A racing sum
Solution: A racing sum
Here is a possible solution to the task.
Code
say (1..50).race.map(* ** 2).grep(* %% 2).sum;🦋 You can find the source code in the file parallel-sum.raku.
Output
22100Comments
.raceruns the whole chain — squaring each number and filtering for the even squares — in parallel, and, unlike.hyper, does not promise to return the elements in order.That is fine here because the final step is a sum, which is order-independent: the even squares (
2²,4², …,50²) add up to22100no matter what order they arrive in. When you only combine the results (sum, count),.raceis the natural choice and can carry a little less overhead than.hyper.