# Memoization and packages

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

f[arg,Memoization->True]


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.

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

BeginPackage["MyPackage"];

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

foo;
DisableMemoization;

Begin["Private"];

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]
]

End[];
EndPackage[];


You can restrict names used by DisableMemoization.

After DisableMemoization` no more memoization.

• But that would leave the user with no way to turm memozation back on, would it? – mmeent Jan 9 at 10:00
• @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. – Kuba Jan 9 at 10:01
• @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. – Kuba Jan 9 at 10:04
• I did not think about memoized contents - I usually restart the kernel and reload the packages. – Per Alexandersson Jan 9 at 12:09
• @PerAlexandersson whatever fit your needs, just make it clear, otherwise it may be slightly too broad. – Kuba Jan 9 at 12:11