-
-
Save reusee/b9a447e3d00d5ae59bfecc01222073ee to your computer and use it in GitHub Desktop.
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
package main | |
import "fmt" | |
func cached( | |
fn func(int) int, | |
) ( | |
decorated func(int) int, | |
) { | |
cache := make(map[int]int) | |
return func(n int) int { | |
if res, ok := cache[n]; ok { | |
return res | |
} | |
res := fn(n) | |
cache[n] = res | |
return res | |
} | |
} | |
func main() { | |
var fib func(int)int | |
fib = cached(func(n int) int { | |
if n <= 1 { | |
return n | |
} | |
return fib(n-1) + fib(n-2) | |
}) | |
fmt.Printf("%d\n", fib(10)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment