Perl6 Lives!

cyocum on 2008-12-07T14:45:07

Ok, this has probably been done by someone else who is better than me elsewhere but I just wanted to show off some of Perl6 and the fact that you can code in Perl6 and that is just damn cool.

use v6;

say factorial(10);

sub factorial(Int $int) {
  my $fac_times = sub(Int $n, Int $acc) {
    if($n == 0) {
      return $acc;
    }
    
    return $fac_times($n - 1, $acc * $n);
  };

  die "Wrong argument!!" if $int < 0;
  return $fac_times($int, 1);
}

What this code does is translate the code from the Wikipedia article on tail recursion from Scheme to Perl6 for the factorial function. It even runs pretty well on an unoptimized build of parrot+rakudo. Thank you Parrot/Perl6 People!

update: I added the die and removed the useless "else" in the inner sub.


The real way to write factorial in Perl 6:

Aristotle on 2008-12-07T18:54:06

my $fac10 = [*] 1 .. 10;

It isn’t even worth pulling out into a function.

Re:The real way to write factorial in Perl 6:

cyocum on 2008-12-07T19:50:06

Perl Golf still lives, I see. I had started playing around with subsets and had intended to update it with stuff like that but I will just say wow...that is really neat.

Re:The real way to write factorial in Perl 6:

Aristotle on 2008-12-07T20:12:50

It’s not golf! That’s just bog-standard Perl 6. Hyper- and reduce operators are normal part of the repertoire and in fact one of the reasons I am looking forward to v6. They get rid of huge swathes of monkey code… as you just saw. Lots of things that would require loops, which really constitute nothing but accidental complexity, can be expressed by a single operator.

Re:The real way to write factorial in Perl 6:

cyocum on 2008-12-07T20:30:05

Like all good things, I hope Perl 6 will change my perception of programming.

Re:The real way to write factorial in Perl 6:

n1vux on 2008-12-09T00:28:03

This old APL/J and Prolog programmer agrees that Perl6 is my dream languoge, as it has hyper / reduce and grammars/structure-matching search, plus threads, though perhaps without the elegance of Hoare-Dijkstra parallel calculus as I originally envisaged (nor even the terseness of sh's & ).

However, how will the simple [*] 1..$n work or fail when $n is large like 100 or 8.424000e+08 ? Does it magically transform to a generator and tail recursion under the covers, or does it do what it appears to say and fill memory with a low entropy sequence? Fills your swap disk and dies horribly is much worse than throwing floating overflow exception after 200 iterations.

See http://www.perladvent.org/2008/3/ for benchmarks where it doesn't fail for absurd inputs so we can discuss them.

Re:The real way to write factorial in Perl 6:

Aristotle on 2008-12-09T02:23:00

Perl 6 lets you write 1..* (or alternatively 1..Inf). That should answer your question. :-)