You will use
- An
actorwith abebehaviour for the work and a method for the result pooka/list:range,map,fold
The whole program
module main
import pooka/int
import pooka/io
import pooka/list
/// Adds up the squares of a range of numbers, in its own process.
actor Worker {
var total: Int = 0
be sum_squares(from: Int, to: Int) {
// `list.range` stops before its end, so ask for one more.
total = list.fold(list.range(from, to + 1), 0, fn(acc: Int, n: Int) {
acc + n * n
})
}
result() -> Int {
total
}
}
main() {
// Four workers, a quarter of the numbers each.
let ranges = [#(1, 250000), #(250001, 500000), #(500001, 750000), #(
750001,
1000000
)]
let workers = list.map(ranges, fn(range: #(Int, Int)) {
let worker = Worker()
worker.sum_squares(range.0, range.1)
worker
})
// Asking for a result waits until that worker has done its sum.
let parts = list.map(workers, fn(worker: Worker) { worker.result() })
let total = list.fold(parts, 0, fn(acc: Int, part: Int) { acc + part })
io.println("parts: " + int.to_string(list.length(parts)))
io.println("total: " + int.to_string(total))
}
Run it
$ pooka run
parts: 4
total: 333333833333500000
That is the sum of the squares of every number from one to a million, which the formula n(n+1)(2n+1)/6 agrees with.
How it works
- Hand out the work. The first
list.mapcreates aWorkerfor each range and sends itsum_squares. Because that is abebehaviour, sending returns at once, and all four workers start computing side by side, on as many cores as the BEAM has. - Collect the answers. The second
list.mapasks each worker forresult(). A request waits until the worker has handled the messages sent before it, so each answer is the finished sum. - Add them up. A
foldcombines the four parts into the total. - Mind the range.
list.range(from, to)stops beforeto, so the worker asks forto + 1to include its last number.
Try next: time it with time.monotonic_now() and time.duration_between, then compare with one worker doing the whole range.