I am working in a package on symmetric functions, that sometimes are quite expensive to compute. I use memoization extensively, but what is the correct approach for a package intended for the public to utilize memoization?

Should it be an option passed to the function, i.e. something like


for granular control, or should it be a global package option?

What about private functions not exposed to the user, but used by several public methods?

I somewhat dislikes the global option, as one then has a state to keep track of (breaking the pure functional approach).

Note that I am particularly interested in best convention, or what people do in practice. This situation must have appeared before.

  • $\begingroup$ I think at least the package should provide a function that clears the memoization of all package functions. $\endgroup$ – mmeent Jan 9 at 9:19

How about:


  ClearAll["`*", "`*`*"];



  foo[0] = 0;
  foo[x_Integer?Positive] := foo[x] = foo[x - 1] + x;

  DisableMemoization[] := DisableMemoization @ Names["MyPackage`*"];
  DisableMemoization[names:{__String}] := ToExpression[
    names, StandardForm, Function[foo, foo /: (foo[___] = x_) := x]


You can restrict names used by DisableMemoization.

After DisableMemoization no more memoization.

enter image description here

  • $\begingroup$ But that would leave the user with no way to turm memozation back on, would it? $\endgroup$ – mmeent Jan 9 at 10:00
  • $\begingroup$ @mmeent or to clear already memoized content etc. I will hold with edits till OP makes a precise list of wishes. But yes your note is on point. $\endgroup$ – Kuba Jan 9 at 10:01
  • 1
    $\begingroup$ @mmeent is number of calls is meant to be high the small overhead of the upvalue may be an issue so it may be worth to reload definitions without momoization part. $\endgroup$ – Kuba Jan 9 at 10:04
  • $\begingroup$ I did not think about memoized contents - I usually restart the kernel and reload the packages. $\endgroup$ – Per Alexandersson Jan 9 at 12:09
  • $\begingroup$ @PerAlexandersson whatever fit your needs, just make it clear, otherwise it may be slightly too broad. $\endgroup$ – Kuba Jan 9 at 12:11

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.