Skip to content

Instantly share code, notes, and snippets.

@reusee
Last active November 2, 2019 17:40
Show Gist options
  • Save reusee/b9a447e3d00d5ae59bfecc01222073ee to your computer and use it in GitHub Desktop.
Save reusee/b9a447e3d00d5ae59bfecc01222073ee to your computer and use it in GitHub Desktop.
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