daily pastebin goal
18%
SHARE
TWEET

[Perl 6] Using caches in closures.

cwchen Nov 28th, 2017 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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;
RAW Paste Data
Top