Memoize a Function in Larzscript
Cache a function's results so calling it twice with the same input only does the real work once.
cache.memoize() wraps any single-argument function with an LRU cache automatically - the second call with the same argument is a cache hit, not a recomputation, which this example proves by counting real calls to the wrapped function.
larzscript pkg install cache
Code
import "cache" as cache
let calls = 0
let memo = cache.memoize(fn(n) { calls = calls + 1; return n * n })
print(memo["call"](5))
print(memo["call"](5))
print("real calls:", calls)Output
25 25 real calls: 1
Related
larzcacheAn LRU cache with optional per-entry TTL and a one-line memoize() wrapper→Retry with Exponential Backoff in LarzscriptRetry a flaky call a few times, waiting longer between each attempt, instead of failing on the first hiccup or hammering a struggling service.→Implement a State Machine in LarzscriptDeclare states and transitions, fire events, and let the machine reject anything that isn't a legal move - a document workflow (draft -> review -> published) in a few lines.→Paginate a List in LarzscriptSlice a list into pages with the has_next/has_prev/1-based-index bookkeeping every list-showing page needs, without hand-rolling the off-by-one math again.→