Bookmark and Share

Programming idioms

Caching the result of a time-comsuming computation in a symbol's DownValue

f[x_] := f[x] = (Pause[5]; Print["Time consuming definition run!"]; 1);

In[31]:= DownValues[f]
Out[31]= {HoldPattern[f[x_]]:>(f[x]=(Pause[5];Print[Time consuming definition run!];1))}

In[32]:= f[1]//AbsoluteTiming//Timing
During evaluation of In[32]:= Time consuming definition run!
Out[32]= {0.061456,{5.00291,1}}
Out[33]= {7.*10^-6,{1.*10^-6,1}}

In[34]:= DownValues[f]
Out[34]= {HoldPattern[f[1]]:>1,HoldPattern[f[x_]]:>(f[x]=(Pause[5];Print[Time consuming definition run!];1))}

blog comments powered by Disqus