sub f {
my $n = shift;
return $n if $n < 2;
f($n-1) + f($n-2);
}
memoize('f');
print "\n\nFast implementation using CPAN Memoization\n";
foreach my $n ( 1..10 ) {
print ' ' . f( $n );
}
CPAN module Memoize can be used to replace a subroutine with a memoized version. See doc for details.
my %cache;
sub fib {
my $n = shift;
return $cache{$n} if exists $cache{$n};
return $cache{$n} = $n if $n < 2;
return $cache{$n} = fib($n-1) + fib($n-2);
}
print "\n\nCustom memoized implementation\n";
foreach my $n ( 1..10 ) {
print ' ' . fib( $n );
}
Custom memoization of a Fibonacci function, using a hash to cache result values. Should work for any pure function; i.e. stateless and with no side-effects.