Problem
Let's say I have some programming language with only referentially transparent functions. It's well-known that any of these functions can then be memoized. However, it's not always worth it in terms of time or space to memoize functions. What is an algorithm for deciding whether or not it will save space or time to automatically memoize a function?
Example
# likely to benefit from memoization
def fact(n):
return 1 if n == 0 else n * fact(n - 1)
# unlikely to benefit from memoization
def inc(x):
return x + 1
My use case
I have a Lisp interpreter as a side-project, which restricts itself to a purely functional subset of Lisp. I want to memoize functions, but I don't want to blindly decide what should and should not be memoized.
Additional info
The solution could either operate using static code analysis, or it could operate during the lifetime of the program, or it could operate over several runs of a program.
The solution doesn't have to be perfect; it could just be a heuristic which is right a good amount of the time.