Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Cache computations like Once but with a maximum number of cached values
ResourceFunction["LimitedCache"][expr] evaluates expr and store results in the "Default" or return previously cached results. | |
ResourceFunction["LimitedCache"][expr,n] caches the result of expr setting the maximum cache size to n, if this is a new cache. | |
ResourceFunction["LimitedCache"][expr,n,name] caches the result of expr in a cache labeled name. | |
ResourceFunction["LimitedCache"]["Reset"] removes the contents of the "Default" cache and set the maximum number of items to store to 100. | |
ResourceFunction["LimitedCache"]["Reset",n,name] removes the contents of cache and reset the maximum number of items to store. | |
ResourceFunction["LimitedCache"]["State",name] returns the DataStructure representing the cache state. |
The first time LimitedCache is used, the value is computed:
In[1]:= | ![]() |
Out[1]= | ![]() |
No evaluation is performed when the computation result is in the cache from a previous calculation:
In[2]:= | ![]() |
Out[2]= | ![]() |
By default, a maximum of 100 values will be cached, so evaluations that get discarded will be recomputed:
In[3]:= | ![]() |
Out[3]= | ![]() |
In[4]:= | ![]() |
Out[4]= | ![]() |
The first use of LimitedCache sets the size of the cache:
In[5]:= | ![]() |
Out[5]= | ![]() |
In[6]:= | ![]() |
Out[6]= | ![]() |
In[7]:= | ![]() |
Out[7]= | ![]() |
You can change the cache size, in which case all previously cached values will be discarded:
In[8]:= | ![]() |
Out[9]= | ![]() |
By default all cached values share the same cache with least recently used values being discarded first. If you need to maintain separate caches for different tasks you can provide a cache name:
In[10]:= | ![]() |
Out[10]= | ![]() |
In[11]:= | ![]() |
Out[11]= | ![]() |
In[12]:= | ![]() |
Out[12]= | ![]() |
The data is stored in a DataStructure. This can be accessed directly and supports all operations supported by the "LeastRecentlyUsedCache” DataStructure:
In[13]:= | ![]() |
Out[13]= | ![]() |
In[14]:= | ![]() |
Out[14]= | ![]() |
The typical application is to memoize function evaluations that are likely to be repeated many times. For example this double-recursive method for calculate Fibonacci numbers recomputes many values:
In[15]:= | ![]() |
Out[15]= | ![]() |
By caching some of the values, you can prevent much of the recursion and improve the evaluation time:
In[16]:= | ![]() |
Out[16]= | ![]() |
This work is licensed under a Creative Commons Attribution 4.0 International License