A couple of syntax sweets in Raku

When working on preparing data for the covid.observer site, I discovered a couple of interesting findings, which I did not notice earlier or did not pay much attention to it.

When working on preparing data for the covid.observer site, I discovered a couple of interesting findings, which I did not notice earlier or did not pay much attention to it.

Scanning two arrays together

The first construct allows us to scan two different arrays in a single loop. For example, let’s print a table with translations of weekdays:

my @English = <Monday Tuesday Wednesday Thursday
               Friday Saturday Sunday>;
my @Latvian = <pirmdiena otrdiena trešdiena ceturtdiena 
               piektdiena sestdiena svētdiena>;

A traditional way would be to use an index:

for 0 ..^ @English -> $index {
    say "@English[$index] = @Latvian[$index]";
}

In Raku, you can use the Z meta-operator to create a sequence of lists so that you get one element from each array (actually, lists are expected as input) at a time:

for @English Z @Latvian -> ($english, $latvian) {
    say "$english is $latvian in Latvian.";
}

Beware to use parentheses as otherwise you get two two-element lists. Here is the modification that extracts the elements from the list inside the loop body:

for @English Z @Latvian -> $list {
    # say $list.^name; # List
    say "$list[0] (en)\t= $list[1] (lv)";
}

Using [-]

Another interesting use case is the usage of the reduction operator. For me, the most often usage would be getting a sum via [+]:

my @data = 1, 2, 3, 4, 5;
say [+] @data; # 15

And I used this for the above-mentioned site to get some totals, for example:

[+] %totals.values.map: *<confirmed>;
%daily-total{$date} = [+] %per-country.values;

Although I know that having the [+] form means putting + between the elements, I did not actually think that the sign before the first element is also a plus, but it is not the + from the surrounding meta-operator.

I had to get the number of active cases of Coronavirus, and thus the formula was straightforward:

my %data =
    confirmed => 100,
    failed    => 1,
    recovered => 70;

my $active = %data<confirmed> - %data<failed> - %data<recovered>;
say $active;

This can be re-written in a compact form with [-] applied to the slice:

my $active = [-] %data<confirmed recovered failed>;
say $active;

The first element, %data<confirmed>, enters as is (with a unary + in mind), while the other two items are subtracted. Which is exactly what I needed.

I hope you like my two simple but very useful findings.

The source codes with the tests from this post are available on GitHub. The source code of an ad-hoc script generating static pages for the website can be found in its own repository.

2 thoughts on “A couple of syntax sweets in Raku”

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code