# How to memoize with patterns? [duplicate]

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?

• If the solutions in the linked thread do not apply to your problem, please edit your question to explain what doesn't work in your actual problem. – J. M.'s ennui Sep 22 '20 at 12:12
• @J.M. Oh thanks - I honestly searched but could not find it. But I am not sure whether to delete my question or not: certainly the answers to that question easily answer mine. On the other hand, it might be that for somebody with a similar question this one is easier to find. What would you do? – მამუკა ჯიბლაძე Sep 22 '20 at 12:20
• @J.M. Also, these answers, although all beautiful, are quite different. Do you remember which one was the most useful for you? – მამუკა ჯიბლაძე Sep 22 '20 at 12:29
• I think keeping this dupe is fine; as you say, this particular instance uses different keywords that would still be picked up by search. As for what I settled with, I used Leonid's solution a lot. – J. M.'s ennui Sep 22 '20 at 14:52