daily pastebin goal
18%
SHARE
TWEET

[Perl 6] Stateful subroutine demo.

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