rememo/memo
The memoization implementation depends on the build target.
- For the Erlang build target, the cache is a Erlang Term Storage database.
- For the Javascript build target, the cache is a mutable Javascript map.
Functions
pub fn create(apply fun: fn(Set(a, b)) -> c) -> c
Make a new memoization cache, of the appropriate type for the build target. Pass this cache to the function you want to memoize.
This is best used with a use
expression:
use cache <- create()
f(a, b, c, cache)
pub fn get(from cache: Set(a, b), fetch key: a) -> Result(b, Nil)
Manually look up a value from the memoization cache for a given key. Useful if you want to also return intermediate results as well as a final result, for example.
pub fn memoize(
with cache: Set(a, b),
this key: a,
apply fun: fn() -> b,
) -> b
Look up the value associated with the given key in the memoization cache, and return it if it exists. If it doesn’t exist, evaluate the callback function and update the cache with the value it returns.
This works well with a use
expression:
fn f(a, b, c, cache) {
use <- memoize(cache, #(a, b, c))
// function body goes here
}