Course of Raku / Functional, concurrent, reactive, and web programming / Concurrent programming / Channels / Exercises / Sum a channel

Solution: Sum a channel

Here is a possible solution to the task.

Code

my $c = Channel.new;
start {
    $c.send($_) for 1..6;
    $c.close;
}

say [+] $c.list;

🦋 You can find the source code in the file channel-sum.raku.

Output

21

Comments

  1. The start block is the producer: it sends the six values on a background thread and then closes the channel.

  2. On the main thread, .list waits for the channel to be closed, collecting every value safely across the thread boundary. The reduce metaoperator [+] then adds them: 1 + 2 + … + 6 is 21.

Course navigation

Sum a channel   |   Drain a channel