Home > Raku > Looplessly simple

Looplessly simple

PWC#153 is asking us to do two things that are almost comically simple, given we omit loops.

Task one would like us to output the first 10 left factorials.

sub MAIN() {
    my \leftfact = [\+] 0, 1, * * ++$ … ∞;
    say leftfact[1..10];
}

I’m doing so by writing down the definition of left factorials as a sequence and then indexing into the resulting lazy list.

In the 2nd task we need to check if the sum of the factorials of a digit equal that number.

sub MAIN(Int() $n) {
    my \fact = 1, * * ++$ … ∞;
    say fact[$n.comb].sum == $n ?? 1 !! 0
}

Again, I write down the definition of a factorial to get a lazy list in return. Then I can index into that list with a list of chars. Thankfully, Raku is considered enough to turn that list of chars into Ints for me. The sum is then checked against the whole number.

If you wonder what numbers are factorions, we can calculate them all.

my \fact = 1, * * ++$ … ∞;
fact[0..10];
.say for (^∞).hyper(:batch(1000)).grep({ fact[.comb].sum == .Int });

Hypering and sequences don’t really mix. State variables even less so. Luckily we only ever need the factorials of 0 to 10. I prime the lazy list with those values and happily hyper away.

I had a peak into the solutions on Rosattacode for left factorials. While scrolling past so many loops I had to think of Mr T.

Categories: Raku