Created
March 30, 2017 16:20
-
-
Save Cornpop456/1d21c0b81171143f137e0721c985c4fd to your computer and use it in GitHub Desktop.
Memoiz fibonaci
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" | |
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