Raku Books / Perl 6 at a Glance / New Concepts / Promises
An example
Finally, a funny example of how promises can be used for implementing the sleep sort algorithm. In sleep sort, every integer number, consumed from the input, creates a delay proportional to its value. As the sleep is over, the number is printed out.
Promises are exactly the things that will execute the code and tell
the result after they are done. Here, a list of promises is created, and
then the programme waits until all of them are done (this time, we do it
using the await keyword).
my @promises;
for @*ARGS -> $a {
@promises.push(start {
sleep $a;
say $a;
})
}
await(|@promises);🖥 This program reads the local environment (files, directories, or the command line), so it runs on your own computer but not in the sandboxed in-browser engine.
Provide the programme with a list of integers:
$ perl6 sleep-sort.pl 3 7 4 9 1 6 2 5CodeBlockPlaceholder3raku-local await do for @*ARGS { start { sleep $; say $; } } ```
First, we use the $_ variable here and thus don’t have
to declare $a. Second, notice the do for
combination, which returns the result of each loop iteration. The
following code will help you to understand how that works:
my @a = do for 1..5 {$_ * 2};
say @a; # [2 4 6 8 10]