Memoized functions are functions which remember values they have found.
Look in the doc center for some background on this in Mathematica, if necessary.
Suppose you have the following definition
f[0] = f[1] = 1
f[x_] := f[x] = f[x - 1] + f[x - 2]
in one of your packages. A user may load the package and start asking right away f[1000].
This will trigger a $RecursionLimit::reclim error message and abort.
Even if the user then tries something smaller, say f[20], by now the definition of f is corrupt and the result is not good anymore.Of course the package developer might increase the recursion limit and warn the user, but my question is:
How can you improve the f definition so that if the user asks for f[1000] he/she gets the answer without any problem? I am interested in a way to trap the user input, analyze it and take whatever steps are necessary to evaluate f[1000].
I can easily imagine that one can change the recursion limit if the input is more than 255 (and then bring it back to the original level), but what I would really like to see is, if there is a way for the f to find out how many values it “knows” (fknownvalues) and accept any input <=fknownvalues+$RecursionLimit without problems or increase the $RecursionLimit if the input is higher.
Thank you for your help
Here is the code assuming that you can determine a value of
$RecursionLimitfrom the value of the input argument:I am using a local function
ffto do the main work, whilefjust calls it wrapped inBlockwith a proper value for$RecursionLimit:EDIT
If you want to be more precise with the setting of
$RecursionLimit, you can modify the part of the code above as:The
Printstatement is here for illustration. The value10is rather arbitrary – to get a lower bound on it, one has to compute the necessary depth of recursion, and take into account that the number of known results isLength[DownValues[ff]] - 2(sinceffhas 2 general definitions). Here is some usage:If you also want to limit the maximal
$RecursionLimitpossible, this is also easy to do, along the same lines. Here, for example, we will limit it to 10000 (again, this goes insideModule):For example: