I assume this could be fixed by using a lambda instead of a top level function if you only want to occasionally call such a function, and don't need the whole memoization table around all the time?
Yes, although you need to make sure it doesn't get optimized away.