[Perl 6] Using caches in closures.
sub fib {
my %cache;
%cache{0} = 0;
%cache{1} = 1;
sub f(Int $n where $n >= 0) {
if %cache{$n}:exists {
return %cache{$n};
}
my $out = f($n - 1) + f($n - 2);
%cache{$n} = $out;
$out;
};
}
my $f = fib();
$f(10).say;
Comments
0 B
|👍
/👎
0 B
|👍
/👎