Skip to content

Instantly share code, notes, and snippets.

@shazow
Last active December 22, 2015 02:59
Show Gist options
  • Save shazow/6407185 to your computer and use it in GitHub Desktop.
Save shazow/6407185 to your computer and use it in GitHub Desktop.
Generic memoizer in Go. (http://play.golang.org/p/ct8ySJ3eh4)
package main
import (
"errors"
"fmt"
"reflect"
"runtime"
)
var ErrMissedCache = errors.New("Memoizer: Missed cache.")
type GenericFunc func(...interface{}) interface{}
type Memoizer interface {
getKey(f GenericFunc, args []interface{}) string
getCache(key string, object *interface{}) error
setCache(key string, object *interface{}) error
Call(f func() interface{}) interface{}
}
type DummyMemoizer struct {
storage map[string]interface{}
}
func (m *DummyMemoizer) getCache(key string, object *interface{}) error {
r, ok := m.storage[key]
object = &r
if !ok {
return ErrMissedCache
}
return nil
}
func (m *DummyMemoizer) setCache(key string, object *interface{}) error {
m.storage[key] = object
return nil
}
func (m *DummyMemoizer) Call(f interface{}, callArgs ...interface{}) interface{} {
fName := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
// TODO: Hash function name + args?
key := fName + ":" + fmt.Sprint(callArgs)
var r interface{}
err := m.getCache(key, &r)
if err == nil {
return r
}
reflectArgs := make([]reflect.Value, len(callArgs))
for i, arg := range callArgs {
reflectArgs[i] = reflect.ValueOf(arg)
}
r = reflect.ValueOf(f).Call(reflectArgs)
m.setCache(key, &r)
return r
}
var counter int = 0
func IncrementCounter(by int) int {
fmt.Println("Executing IncrementCounter")
counter += by
return counter
}
func main() {
cache := DummyMemoizer{}
cache.storage = make(map[string]interface{})
cache.Call(IncrementCounter, 1) // counter == 1 (incremented)
cache.Call(IncrementCounter, 2) // counter == 3 (incremented)
cache.Call(IncrementCounter, 2) // counter == 3 (cached)
cache.Call(IncrementCounter, 5) // counter == 8 (incremented)
cache.Call(IncrementCounter, 5) // counter == 8 (cached)
fmt.Println("Final counter:", counter)
}
@shazow
Copy link
Author

shazow commented Sep 2, 2013

Yay it's working now. Wonder what the performance implications of using reflect's Call() are.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment