Once
Once[expr]
evaluates expr once in each Wolfram Language session, always returning the result from the first evaluation.
Once[expr,loc]
evaluates expr once and caches the result in persistence location loc.
Details and Options
- When first used in a session, Once[expr] evaluates expr and returns the result.
- Subsequent uses of Once[expr] do not evaluate expr again, and return the result from when expr was first evaluated.
- Once has attribute HoldFirst.
- Once[expr] is equivalent to Once[expr,"KernelSession"].
- In Once[expr,loc], possible forms for the persistence location loc include:
-
PersistenceLocation["type"] "Local", "Cloud", "FrontEndSession", etc. locations "type" equivalent to PersistenceLocation["type"] PersistenceLocation["type","base"] location with a particular base (directory etc.) "type""base" equivalent to PersistenceLocation["type","base"] - Unset[Once[expr]] or Unset[Once[expr,loc]] removes any stored value for expr.
- Once has the following options:
-
ExpirationDate None when the cache should expire PersistenceTime None how long the cache should persist - If Once[expr,…] is evaluated after a cached result is specified to have expired, then expr will be evaluated again.
Examples
open allclose allBasic Examples (1)
Scope (2)
Options (2)
PersistenceTime (1)
Specify that the result of Once should be remembered only for 5 seconds:
After the time specified has elapsed, the value is recomputed:
Applications (2)
Properties & Relations (3)
Possible Issues (2)
Neat Examples (1)
Use Once for a form of dynamic programming to turn recursion into iteration:
Find the number of cached values generated:
Remove the cached values before redoing the timing experiment:
Text
Wolfram Research (2016), Once, Wolfram Language function, https://reference.wolfram.com/language/ref/Once.html (updated 2019).
CMS
Wolfram Language. 2016. "Once." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2019. https://reference.wolfram.com/language/ref/Once.html.
APA
Wolfram Language. (2016). Once. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Once.html