10
$\begingroup$

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?

$\endgroup$
4
  • 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
    Commented Aug 25, 2015 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$
    – user1722
    Commented Aug 25, 2015 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
    Commented Aug 25, 2015 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
    Commented Aug 25, 2015 at 14:24

1 Answer 1

12
$\begingroup$
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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.