Created
May 18, 2020 12:52
-
-
Save tmtvl/e9d1d78885fc702298b76d3dfd0e518b to your computer and use it in GitHub Desktop.
Memoized fibonacci in Raku
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env raku | |
use v6; | |
sub memoize-walk (Code $calc --> Code) { | |
my Int @cache; | |
return sub (Int $n --> Int) { | |
return @cache[$n] if @cache[$n]; | |
my Int $result = $calc($n); | |
@cache[$n] = $result; | |
} | |
} | |
my Code $fib = memoize-walk sub (Int $n --> Int) { | |
return 1 if $n < 2; | |
return $fib($n - 1) + $fib($n - 2); | |
} | |
sub MAIN (Int $n = 33) { | |
say $fib($n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment