Each time a function is called, if it’s result for a given set of argument values is not yet memoized I’d like to put the result into an in-memory table. One column is meant to store a result, others to store arguments values.
How do I best implement this? Arguments are of diverse types, including some enums.
In C# I’d generally use DataTable. Is there an equivalent in Scala?
You could use a
mutable.Map[TupleN[A1, A2, ..., AN], R], or if memory is a concern, a WeakHashMap[1]. The definitions below (built on the memoization code from michid’s blog) allow you to easily memoize functions with multiple arguments. For example:Definitions:
The fixed-point combinator (
Memoize.Y) makes it possible to memoize recursive functions:[1] WeakHashMap does not work well as a cache. See http://www.codeinstructions.com/2008/09/weakhashmap-is-not-cache-understanding.html and this related question.