2
$\begingroup$

I am fairly new to Mathematica. I am working my way through a number of books. I have been looking at the use of SetDelayed and want to confirm that my understanding is correct. I define a function as follows.

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

When I evaluate ?f, I can see a rule for this function. Now each time I evaluate f, I see another rule is created for f. So by declaring the function as above, I ensure that for any given value of x the function will only be evaluated once.

Suppose I had declared functions f and g as follows.

f[x_] := f[x] = Sin[x] + Cos[x];
g[x_] := Sin[x] + Cos[x];

Am I correct in saying that, for any given x, f will only be evaluated once? That is, for a given value of x, Sin[x] and Cos[x] will only be called once; whereas in the case of g, each time g is called, Mathematica will evaluate both Sin[x] and Cos[x]? Will using Trace confirm this?

$\endgroup$
7
  • 1
    $\begingroup$ Yes, you're correct. It's more apparent with something like f[x_] := f[x] = (Print[x];x). $\endgroup$
    – Szabolcs
    Commented Mar 8, 2013 at 13:37
  • $\begingroup$ Thanks. Is it possible to run out of space in the global rule/name space ? In effect each time i call f[x] mathematica is creating a new rule so if i call the function n times i end up with n rules. $\endgroup$ Commented Mar 8, 2013 at 13:42
  • $\begingroup$ It is possible to run out of memory with this technique, but with most current computers this not the problem it was, say, in the 1990s. Mathematica is very good at getting all the memory it needs. $\endgroup$
    – m_goldberg
    Commented Mar 8, 2013 at 13:53
  • $\begingroup$ Search for memoization on this page There's an implementation that will auto-free memory if too many results are remembered, but it only works for numerical arguments. I believe there were better implementations somewhere on this site. Someone will hopefully find them and give you a link. $\endgroup$
    – Szabolcs
    Commented Mar 8, 2013 at 14:19

0

Browse other questions tagged or ask your own question.