Current section
Files
Jump to
Current section
Files
src/rememo@memo.erl
-module(rememo@memo).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/rememo/memo.gleam").
-export([create/1, set/3, get/2, memoize/3]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
?MODULEDOC(
" The memoization implementation depends on the build target.\n"
" \n"
" * For the Erlang build target, the cache is a [Erlang Term Storage \n"
" database](https://www.erlang.org/doc/apps/erts/persistent_term.html).\n"
" * For the Javascript build target, the cache is a [mutable Javascript map](\n"
" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map).\n"
).
-file("src/rememo/memo.gleam", 18).
?DOC(
" Make a new memoization cache, of the appropriate type for the build target.\n"
" Pass this cache to the function you want to memoize.\n"
" \n"
" This is best used with a `use` expression:\n"
" ```gleam\n"
" use cache <- create()\n"
" f(a, b, c, cache)\n"
" ```\n"
).
-spec create(fun((internal@carpenter@table:set(any(), any())) -> KGM)) -> KGM.
create(Fun) ->
internal@ets@memo:create(Fun).
-file("src/rememo/memo.gleam", 24).
?DOC(
" Manually add a key-value pair to the memoization cache.\n"
" Useful if you need to pre-seed the cache with a starting value, for example.\n"
).
-spec set(internal@carpenter@table:set(KGA, KGB), KGA, KGB) -> nil.
set(Cache, Key, Value) ->
internal@ets@memo:set(Cache, Key, Value).
-file("src/rememo/memo.gleam", 30).
?DOC(
" Manually look up a value from the memoization cache for a given key.\n"
" Useful if you want to also return intermediate results as well as a final result, for example.\n"
).
-spec get(internal@carpenter@table:set(KGE, KGQ), KGE) -> {ok, KGQ} |
{error, nil}.
get(Cache, Key) ->
internal@ets@memo:get(Cache, Key).
-file("src/rememo/memo.gleam", 46).
?DOC(
" Look up the value associated with the given key in the memoization cache,\n"
" and return it if it exists. If it doesn't exist, evaluate the callback function\n"
" and update the cache with the value it returns.\n"
" \n"
" This works well with a `use` expression:\n"
" ```gleam\n"
" fn f(a, b, c, cache) {\n"
" use <- memoize(cache, #(a, b, c))\n"
" // function body goes here\n"
" }\n"
" ```\n"
).
-spec memoize(internal@carpenter@table:set(KGH, KGS), KGH, fun(() -> KGS)) -> KGS.
memoize(Cache, Key, Fun) ->
internal@ets@memo:memoize(Cache, Key, Fun).