Perl6 code

jhuni on 2010-03-18T07:00:17

I uploaded a repository containing lots of perl6 examples/code that I have written over the years:



Most of that code is stuff that I put on wikis such as perl6.wikia.com. I will probably add more to that repository over the days to come, however, I intend to focus on more practical applications now then just learning and examples. But in the mean time I found this page on Rosetta code and I would like to briefly rant about it:



That page asks you to solve the problem of printing the following triangle of asterisks:

*
**
***
****
*****

I just feel that the solutions written in Perl6 on that page are more elegant then those written in any of the other languages. Part of this is the quantity of characters. Perl6 has the least, perhaps due to the great new operators and the fact that you can exclude parenthesis.

import sys
for i in xrange(5):
    for j in xrange(i+1):
        sys.stdout.write("*")
    print


This solution from that link makes me wonder... who ever said Python is readable? How many people actually know what stdout is, and how many people are going to know what a blank print statement does? Admittely, that code is constrained because Rosetta code asked that two nested loops be used, so lets look at a more "Pythonic" way of doing things:

for i in range(1,6):
    print '*' * i


I don't think that code is actually that much better because the * character is used to replicate strings and it just so happens to be the character which is being replicated! Furthermore, it is confusing that the range is represented as range(1,6) when the actual triangle you need to print is 1..5.

say '*' x $_ for 1..5;

How about that? It is only 22 characters, as opposed to 96 and 38 for the Python solutions. Even constrained by the condition that you have to use two for loops, the perl6 solution is still elegant because you can leave off parenthesis.

([\~] "*" xx 5).join("\n").say;

This is another solution using triangular reduction operators, which are a new feature in Perl6. It doesn't seem to be as elegant as the previous example, but I still think it is nice. Related to that, you can calculate the number of asteriks in that triangle using reduction operators: ([+] 1..5 == 15). Anyways I think that is enough of a rant for today =/


Hear hear !

thickas on 2010-03-19T06:48:08

Hard to disagree.

The P6 stuff looks nice. Thanks for pointing it out.