Advertisement
cwchen

[Perl 6] Stateful subroutine demo.

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