This is a basic memoization method for Gleam on the Javascript build target, for caching and reusing the results of function calls when possible. If you need memoization on Erlang, use rememo_erlang instead.
Adding to and reading from the memoization cache incurs some overhead, but in situations that call for it, like dynamic programming problems where using memoization allows you to avoid evaluating the same basic subproblem hundreds or thousands of times, the tradeoff is worthwhile. Always benchmark your code when in doubt.
gleam add rememo_javascript@1import rememo/memo
pub fn main() {
// Make the mutable state that holds the cached values
// for the duration of this block, return the final value of
// the called function, then delete the mutable state
use cache <- memo.create()
echo fib(300, cache)
}
fn fib(n, cache) {
// Check if a value exists for the key n
// Use it if it exists, update the cache if it doesn't
use <- memo.memoize(cache, n)
case n {
1 | 2 -> 1
n -> fib(n - 1, cache) + fib(n - 2, cache)
}
}Further documentation can be found at https://hexdocs.pm/rememo_javascript.
Suggestions and pull requests are welcome.