Advertisement
cwchen

[Perl 6] Using caches in closures.

Nov 28th, 2017
3,466
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 0.31 KB | None | 0 0
  1. sub fib {
  2.     my %cache;
  3.     %cache{0} = 0;
  4.     %cache{1} = 1;
  5.    
  6.     sub f(Int $n where $n >= 0) {
  7.         if %cache{$n}:exists {
  8.             return %cache{$n};
  9.         }
  10.    
  11.         my $out = f($n - 1) + f($n - 2);
  12.         %cache{$n} = $out;
  13.    
  14.         $out;
  15.     };
  16. }
  17.  
  18. my $f = fib();
  19. $f(10).say;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement