App patterns · real, tested code

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