Easiest way would probably be to just use the existing `memo` package which sounds like it does exactly what you want: <https://github.com/andreaferretti/memo>
Barring that I assume it's implementation is very close to what you're actually looking to do.
