๐Ÿ“˜ Sleep Sort in Perl 6

Implement the Sleep Sort algorithm for a few small positive integer values.

The Sleep Sortis a funny implementation of the sorting algorithm. For each input value, an asynchronous thread starts, which waits for the number of seconds equals to the input number and then prints it. So, if all the threads are spawned simultaneously, the output of the program contains the sorted list.

Here is the solution in Perl 6. On the next page, we will go through the bits of it and explain all the important moments.

await gather for @*ARGS -> $value {
    take start {
        sleep $value/10;
        say $value;
    }
}

Pass the values via the command line, and get them sorted.

$ perl6 sleep-sort.pl 9 10 2 8 5 7 6 4 1 3
1
2
3
...
8
9
10

The input values from the command line come to theย @*ARGS array. The first step is to iterate over the array:

for @*ARGS -> $value {    
     . . .
}

For eachย $value, theย startblock creates a promise with a code block that waits for the time that is proportional to the value and prints the value after that time.

start {
    sleep $value/10;
    say $value;
}

Dividing the value by ten speeds up the program. On the other hand, the delay should not be too small to avoid race conditions between different threads.

After a separate promise has been created for each input number, the program has to wait until all of them are kept. To achieve that, theย gatherโ€”take construction is used. Theย take keyword adds another promise to a sequence, which is then returned as a whole by theย gather keyword.

gather for @*ARGS -> $value {
    take start {
        . . .
    }
}

Finally, theย await routine ensures the program does not quit until all the promises are kept or, in other words, until all the numbers are printed.

await gather . . . {
ย ย ย ย take start {
ย ย ย ย ย ย ย ย . . .
ย ย ย ย }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s