Skip to content

Instantly share code, notes, and snippets.

@belden
Created December 2, 2013 23:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belden/7760683 to your computer and use it in GitHub Desktop.
Save belden/7760683 to your computer and use it in GitHub Desktop.
Tail recursion pattern in Perl - for some reason people say Perl doesn't have tail recursion; you just need to do a little extra work.
#!/usr/bin/env perl
use strict;
use warnings;
use bigrat;
my $n = shift || 100;
print "$n! = " . tail_factorial($n) . "\n";
{
my $fac;
sub tail_factorial {
local @_ = @_;
$fac = 1;
&_tail_factorial;
return $fac;
}
sub _tail_factorial {
return if $_[0] < 2;
$fac *= $_[0];
$_[0]--;
goto &_tail_factorial; # tail recursion, yo
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment