cwchen icon

[Perl 6] Using caches in closures.

cwchen | PRO | 11/29/17 02:11:40 AM UTC | 0 ⭐ | 12305 👁️ | Never ⏰ | []
Perl 6 |

0 B

|

None

|

0 👍

/

0 👎

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

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎