Use sequences in Raku

Here’s is an update to my previous solutions that uses sequences in Raku.

Hi, here’s is an update to my previous solutions to the Weekly Challenge 69. The task is to generate a sequence of the strings based on the following definition:

S0 = ‘’
Sn
= concat(Sn-1, 0, reverse(XOR Sn-1))

I solved it using multi-functions, which are really good when you have different conditions for (usually) small initial numbers.

multi sub S(0) {''}
multi sub S(1) {'0'}
multi sub S($n) {
    my $prev = S($n - 1);
    $prev ~ '0' ~ $prev.flip.trans('01' => '10')
}

On the other hand, the task defines the row of numbers as a sequence, and Raku’s Seq can be used here!

my @s = '', {
    $^a ~ 0 ~ $^a.flip.trans('01' => '10')
} ... *;

To print the numbers, you now directly access a lazy array:

.say for @s[^9];

If you want to keep the function, you can use a state variable in it:

sub S($n) {
    state @s = '', {
        $^a ~ 0 ~ $^a.flip.trans('01' => '10')
    } ... *;

    @s[$n]
}

say S($_) for ^9;

What’s the morale of this story?

Don’t forget about the powerful three dots that you have for free in Raku! Sometimes it needs to change your mindset before you can think of it.

GitHub repository
Navigation to the Raku challenges post series

One thought on “Use sequences 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