# Can I memoize retroactively?

I have a function defined something like this:

f[x_] := Module[...];


I can easily write a memoized version of it like this:

f2[x_] := f2[x] = f[x];


And then replace every instance of f[...] with f2[...] in my code.

However, I have code that uses f directly in many places (the actual situation is more complicated: I have several such functions that call each other).

Can I retroactively memoize f? Something like this:

(* set ftemp to the original version of f *)
ftemp = f;
(* memoize the original f *)
f[x_] := f[x] = ftemp[x];


This (and several variants) don't work, probably because f is defined as := and = (ie, it's evaluated when called).

When I do ?f, I see the definition of f. If I could somehow copy this to ftemp, I think my trick above would work.

Any thoughts on how I could do this and/or solve the general problem of memoizing retroactively?

• So you are saying just f[x_] := f[x] = ...' wouldn't work? I'm confused about the meaning of "retroactively" here. Memoization after what? You mean in a running session? – sebhofer Aug 25 '15 at 13:58
• I only want to memoize f in a specific file. I don't want to rewrite the definition of f in the file where it's defined. Normally, I would use f without memoization, but, in this one special case, I want to memoize. – barrycarter Aug 25 '15 at 14:08
• I'm still not sure I understand... You are saying you want to switch on memoization on the fly? – sebhofer Aug 25 '15 at 14:23
• ...because when you say you want to use memoization only "in a specific file" I would suggest to just use the definition of f2 from your post... – sebhofer Aug 25 '15 at 14:24

f[x_] := x^2

h is now equal to the original f, and f is a memoized version of it.
Some kinds of definitions would require a more specific replacement rule than /. f -> h`, for example recursive functions.