I have a loop in which several values of a function are computed, depending on the values for that function that were computed in the previous iteration of the loop. This could be implemented recursively, but it would result in very many downvalues for the function. I want to save the memory that those downvalues would occupy. My plan is to maintain two functions; to overwrite the old one with the new one in each iteration of the loop; to clear the new function, and then to compute the values of the new function depending on the values of the old function.

But unfortunately in spite of my using "Set" instead of "SetDelayed", it seems that as soon as the new function is Cleared, the old function forgets its definition:

Clear[funA, funB]
funA[3] = 7
funB = funA

gives the output:


all of which is what I wanted, except that I want the last output to be "7", not "funA[3]".

I have experimented with "SetDelayed" (:=) instead of "Set" (=) and with "Evaluate", but to no avail. What am I doing wrong ?

I have a version of my code that works perfectly, in which instead of having two functions and Clearing the old function, I have a single function, and in each iteration of the loop I "Unset" its values that are no longer required. However, the Unsetting process goes value-by-value in a loop of its own, and takes quite a while.


Try this instead of funB = funA:

DownValues[funB] = DownValues[funA] /. funA -> funB

Or even better: Use Associations.

| improve this answer | |
  • $\begingroup$ Thank you very much ! That worked a treat ! Dare I ask why it works ? The /. funA -> funB part seems particularly mysterious to my small brain. Regarding Associations, I suffered a few headaches with them when I last tried them in earnest. I found several "natural" things quite hard to do, such as extracting images or preimages, or projections and so on. I seem to remember it was partly because of parallel but incompatible (presumably arising historically) syntaxes, such as the differences between Part and Position. $\endgroup$ – Simon Jun 4 at 22:47
  • 1
    $\begingroup$ The /. funA -> funB is not mysterious at all. Have a look at DownValues[funA]. Then you see that the downvalues are stored as delayed rules like {HoldPattern[funA[3]] :> 7}. If you want that rule to apply for funB, then you have to do the replacement. $\endgroup$ – Henrik Schumacher Jun 4 at 22:57

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.