Last active
March 24, 2018 12:19
-
-
Save mostafa-asg/cbe12409e480a7ff92db9f46e3e8cf17 to your computer and use it in GitHub Desktop.
Function Memorization in Go (https://mostafa-asg.github.io/posts/function-memorization-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 main | |
type FuncIntInt func(int) int | |
func memorized(fn FuncIntInt) FuncIntInt { | |
cache := make(map[int]int) | |
return func(input int) int { | |
if val, found := cache[input]; found { | |
println("Read from cache") | |
return val | |
} | |
tmp := fn(input) | |
cache[input] = tmp | |
return tmp | |
} | |
} | |
func main() { | |
var memFact FuncIntInt | |
memFact = memorized(func(n int) int { | |
if n <= 1 { | |
return 1 | |
} | |
return n * memFact(n-1) | |
}) | |
println(memFact(5)) | |
println("-------------") | |
println(memFact(4)) | |
println("-------------") | |
println(memFact(3)) | |
/* -------------------- | |
// OUTPUT : | |
120 | |
------------- | |
Read from cache | |
24 | |
------------- | |
Read from cache | |
6 | |
----------------------*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment