Last active
August 11, 2023 15:01
-
-
Save dimitrilw/4cc3eb1d72d1bdbf6705daea5a6a9653 to your computer and use it in GitHub Desktop.
Go (golang) modular function cache
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
/* memoization outside of the function being memoized | |
The value of this pattern is the modularity of the memoization. | |
This means that if we change it from a Go map to an external | |
DB store, then it's just the memo function that needs editing. | |
Does NOT work with recursive functions. | |
*/ | |
type FnInt_Int func(int) int | |
func memo(fn FnInt_Int) FnInt_Int { | |
// if fn receives multiple args, then recommend a map of string -> result | |
// and then key = Sprintf("%v %v %v", arg1, arg2, arg3) | |
m := map[int]int{} | |
return func(arg int) int { | |
if val, ok := m[arg]; ok { | |
fmt.Println("res from memo:", arg, "->", val) | |
return val | |
} | |
res := fn(arg) | |
m[arg] = res | |
fmt.Println("calc & store in memo:", arg, "->", res) | |
return res | |
} | |
} | |
func DemoFnAddOne(n int) int { return n + 1 } | |
func main() { | |
memDFAO := memo(DemoFnAddOne) | |
fmt.Println("memDFAO 1", memDFAO(1)) | |
fmt.Println("memDFAO 2", memDFAO(2)) | |
fmt.Println("memDFAO 1", memDFAO(1)) | |
} | |
/* output: | |
calc & store in memo: 1 -> 2 | |
memDFAO 1 2 | |
calc & store in memo: 2 -> 3 | |
memDFAO 2 3 | |
res from memo: 1 -> 2 | |
memDFAO 1 2 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment