Created
February 4, 2018 14:05
-
-
Save crgimenes/54090ad87be481a294971fd8e299f84d to your computer and use it in GitHub Desktop.
Memoized fibonacci from `Learning Functional Programming in Go`
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 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