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?

  • 1
    $\begingroup$ 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? $\endgroup$ – sebhofer Aug 25 '15 at 13:58
  • $\begingroup$ 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. $\endgroup$ – barrycarter Aug 25 '15 at 14:08
  • $\begingroup$ I'm still not sure I understand... You are saying you want to switch on memoization on the fly? $\endgroup$ – sebhofer Aug 25 '15 at 14:23
  • $\begingroup$ ...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... $\endgroup$ – sebhofer Aug 25 '15 at 14:24
f[x_] := x^2

DownValues[h] = DownValues[f] /. f -> h;
f[x_] := f[x] = h[x]

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.

  • $\begingroup$ Exactly what I needed, thanks! I was messing around with things like Definition[] but couldn't quite get it to work. $\endgroup$ – barrycarter Aug 25 '15 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.