Skip to content

Instantly share code, notes, and snippets.

@mostafa-asg
Last active March 24, 2018 12:19
Show Gist options
  • Save mostafa-asg/cbe12409e480a7ff92db9f46e3e8cf17 to your computer and use it in GitHub Desktop.
Save mostafa-asg/cbe12409e480a7ff92db9f46e3e8cf17 to your computer and use it in GitHub Desktop.
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