Why I love Perl 6

I've been quietly playing along at home with the Perl Weekly Challenge, and this week's first task was:

Write a script that finds the first square number that has at least 5 distinct digits.

The solution to that is (obviously!) to lazily square every number from 1 to infinity, then comb through each square's digits looking for five or more unique numerals, and immediately output the first such square you find.

Which translates directly to Perl 6:

1..∞ ==> map {$^n²} ==> first {.comb.unique ≥ 5} ==> say();

But the elegance of that solution is not why I love Perl 6.

I love Perl 6 because, if that solution seems too scary to you (too infinite, too lazy, too concurrent, too pipelined, too Unicoded, too declarative, too functional, too much like something that an Erlang guru would code), then Perl 6 will equally allow you to write a plain and simple version: one that's imperative, iterative, block structured, variable-driven, pure ASCII, and more-or-less exactly what you'd write in Perl 5, or even in C:

loop (my $n=1 ;; $n++) {
    my $n_squared = $n ** 2;

    my %unique-digits;
    for (split '', $n_squared, :skip-empty) {
        %unique-digits{$_}++
    }

    if (%unique-digits >= 5) {
        say $n_squared;
        last;
    }
}

Or you could just as easily write a solution somewhere between those two extremes, at whatever level of complexity and decomposition happens to be the sweet spot in your personal comfort zone. For example:

sub find_special_square {
    for 1..Inf -> $n {
        return $n²
            if $n².comb.unique >= 5
    }
}

say find_special_square();

More than any other language I know, Perl 6 lets you write code in precisely the way that suits you best, at whatever happens to be your (team's) current level of coding sophistication, and in whichever style you will later find most readable
...and therefore easiest to maintain.

And that's why I love Perl 6.

Damian

1 Comment

Do use for-loops for unbounded limits or loops that exit prematurely. Only use them for loops that limits are known and will run to completion.

Leave a comment

About Damian Conway

user-pic I blog about Perl.