Course of Raku / Functional, concurrent, reactive, and web programming / Reactive programming / react and whenever / Exercises / Sort into two arrays

Solution: Sort into two arrays

Here is a possible solution to the task.

Code

my @small;
my @big;

react {
    whenever Supply.from-list(4, 42, 7, 100, 15) {
        if $_ > 10 { @big.push($_) }
        else       { @small.push($_) }
    }
}

say @small;
say @big;

🦋 You can find the source code in the file react-collect.raku.

Output

[4 7]
[42 100 15]

Comments

  1. The whenever body is ordinary code, so it can do more than collect — here it decides, routing each value to @big or @small as it arrives. Within each array the values keep their stream order.

  2. The react block waits until the stream is done, so both arrays are complete before they are printed.

Course navigation

Sort into two arrays   |   Two whenevers