Skip to content

Instantly share code, notes, and snippets.

@Cornpop456
Created March 30, 2017 16:20
Show Gist options
  • Save Cornpop456/1d21c0b81171143f137e0721c985c4fd to your computer and use it in GitHub Desktop.
Save Cornpop456/1d21c0b81171143f137e0721c985c4fd to your computer and use it in GitHub Desktop.
Memoiz fibonaci
package main
import "fmt"
type memoizeFunction func(int) interface{}
func fibonacci(n int) interface{} {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fibonacci(n-1).(int) + fibonacci(n-2).(int)
}
}
func memoize(function memoizeFunction) memoizeFunction {
cache := map[int]interface{}{}
wrapped := func(n int) interface{} {
println("I am WRAPED!")
if _, ok := cache[n]; !ok {
cache[n] = function(n)
}
fmt.Println(cache)
return cache[n]
}
return wrapped
}
var new_fib memoizeFunction
func init() {
new_fib = memoize(fibonacci)
}
func main() {
fmt.Println(new_fib(10).(int))
fmt.Println(new_fib(30).(int))
fmt.Println(new_fib(50).(int))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment