Here is an artificial example to explain what I am up to. Define
ClearAll[f]
f[x_, y_] := f[x, y] = If[x == 0, g[y], g[f[x - 1, y]]]
Then AbsoluteTiming[f[10, y]]
gives
{0.0000863, g[g[g[g[g[g[g[g[g[g[g[y]]]]]]]]]]]}
,
whereafter AbsoluteTiming[f[5, y]]
gives
{6.2*10^-6, g[g[g[g[g[g[y]]]]]]}
.
However after that AbsoluteTiming[f[5, z]]
gives
{0.0000487, g[g[g[g[g[g[z]]]]]]}
,
i. e. with z
it takes more time than with y
. This is because the remembered downvalues of f
before evaluating at z
only involve the variable y
- for example, HoldPattern[f[2, y]] :> g[g[g[y]]]
is among them.
If I could memoize something like HoldPattern[f[2, y_]] :> g[g[g[y]]]
instead (that is, with pattern y_
instead of the hardwired variable y
), would not the result be more efficient? If no, why? If yes, how to do it?