Skip to content

Instantly share code, notes, and snippets.

@crgimenes
Created February 4, 2018 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crgimenes/54090ad87be481a294971fd8e299f84d to your computer and use it in GitHub Desktop.
Save crgimenes/54090ad87be481a294971fd8e299f84d to your computer and use it in GitHub Desktop.
Memoized fibonacci from `Learning Functional Programming in Go`
package fibonacci
type Memoized func(int) int
var fibMem = Memoize(fib)
func Memoize(mf Memoized) Memoized {
cache := make(map[int]int)
return func(key int) int {
if val, found := cache[key]; found {
return val
}
temp := mf(key)
cache[key] = temp
return temp
}
}
func FibMemoized(n int) int {
return fibMem(n)
}
func fib(x int) int {
if x == 0 {
return 0
} else if x <= 2 {
return 1
} else {
return fib(x-2) + fib(x-1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment