Perl Weekly Challenge 020

This week I wrote some Perl 6 code for the first time. I did a pretty straight lift of the Perl 5 code, which I wrote first, into Perl 6. When Perl 5 code uses a lot of perl idioms we call it perlish or perly. Should we call Perl 6 that follows that languages idioms something else? In honor of the Rakudo compiler Rakish perhaps? I only bring this up to have an easy way of saying that by simply translating Perl 5 to Perl 6 that my code is probably not particularly rakish. Frankly, probably not that perlish either!

Although not necessary, I decided from the start to use Threads for Part 2. This will allow the easily parallelizable elements of the code, the factoring of many numbers, to be split across multiple CPU cores. In my Perl 6 code I used essentially the same approach but with Promises.

Finally, I'll note that, like last week, for this week's challenges I was able to re-use some code from a previous week. The use of pack/unpack was used in Week 7 and the factoring code is from Week 8.

Part 1

Perl 5

Sample Run

$ perl perl5/ch-1.pl AABBBCDDE
AA
BBB
C
DD
E

Perl 6

Sample Run

$ perl6 perl6/ch-1.rk AABBBCDDE
AA
BBB
C
DD
E

Notes On Part 1

The Perl 5 and Perl 6 version look essentially identical! The only differences are extremely minor: the command line arguments in Perl 6 are in an array named @*ARGS and in order to split a string into a list we need to pass Perl 6 split an empty string which then does pretty much as expected but also adds an empty string at the start and end of the list which needs to be accounted for. 

Part 2

Perl 5

Sample Run

$ perl perl5/ch-2.pl
First amicable pair of numbers: 220 284

Perl 6

Sample Run

$ perl6 perl6/ch-2.rk
First amicable pair of numbers: 220 284

Notes On Part 2

The approach here is to factor and sum the factors of batches of numbers, each batch handled by independent workers, either a separate thread or Promise. When these workers are completed their results are added to a hash of numbers and their factor sums and this hash is then reviewed for amicable numbers. When the first one is found the loop, and the program itself, exits.

The Perl 5 and Perl 6 version again look similar. Promises offer a similar interface to creating a thread. Although differing in many way for all practical purposes the same effect is achieved, computation is split across the available CPU cores, as verified by my Mac's CPU monitor.

Activity across all cores.
Activity across all cores.

The second and third cores are mostly idle but during the brief run of ch-2.rk a quick glance at the CPU monitor verifies their use. In a similar way you could also check out the moar VM's usage in top.

References

I highly recommend Andrew Shitov's Perl 6 at a Glance. This book is my primary reference for Perl 6 and is an excellent resource to have available to you if you already know Perl 5 and would like to get started with Perl 6. 

Comments for this post were locked by the author