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

22100

Comments

  1. .race runs 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.

  2. That is fine here because the final step is a sum, which is order-independent: the even squares (, , …, 50²) add up to 22100 no matter what order they arrive in. When you only combine the results (sum, count), .race is the natural choice and can carry a little less overhead than .hyper.

Course navigation

A racing sum   |   Hyper with a filter