// Row evidence across actors (ADR 0066), the `async` pattern: 4000 // handlers, each in an actor of its own, run a page of 8 parts. Their // `later` runs each part in a new actor, where `within` re-installs the // handler of `ask` that the part, a bundled lambda, performs. The sum // does not depend on the order in which actors run. import std/io import std/process.{type Subject, type proc} effect ask { fn ask :: -> Int } effect async { fn later :: render: send fn() -> Int / -> Int } fn with_ask :: n: Int action: fn() -> a / -> a / { handle { action () } with { ask -> n } } // Each part `action` defers runs in an actor of its own, inside `within`. fn streamed :: within: send fn(send fn() -> Int / ) -> Int action: fn() -> a / , proc | e2> -> a / { handle { action () } with { later render -> { let results = process.subject () let _ = process.spawn fn { process.send results (within render) } process.receive_forever results } } } // `n` parts: the `i`-th asks for the handler's number and multiplies it // by `i`. fn page :: n: Int -> Int / > | r2> { if n == 0 { 0 } else { later fn { ask () * n } + page (n - 1) } } // Handler `k`: its parts see `k`. fn handler :: k: Int parts: Int -> Int / { streamed (fn render { with_ask k fn { render () } }) fn { page parts } } fn spawn_handlers :: k: Int parts: Int results: Subject -> () / { if k > 0 { let _ = process.spawn fn { process.send results (handler k parts) } spawn_handlers (k - 1) parts results } } fn sum :: results: Subject left: Int total: Int -> Int / { if left == 0 { total } else { sum results (left - 1) (total + process.receive_forever results) } } pub fn main :: -> () / { let handlers = 4000 let parts = 8 let results = process.subject () spawn_handlers handlers parts results // Handler `k` sums `k * i` for `i` in 1..8: 36 `k`. io.println ("sum " <> show (sum results handlers 0)) } //> sum 288072000