I have a type which, among other fields, contains a field to cache the result of an expensive operation.
type t = {
(* ... *)
mutable result_cache: int option;
}
where mutable_cache starts as None
. Then there’s this expensive_fun : t -> int
, which in fact first checks if .result_cache
is Some x
, and if yes just returns x
, else actually computes the function, stores the result in .result_cache
and returns the value.
This works fine if there’s just one expensive_fun
. I was to extend it for the case when there are several different expensive_fun
s (which of course return different results, all of which need to be cached). My idea was writing
module M = Map.Make(???)
type t = {
(* ... *)
mutable result_cache: int M.t;
}
where the cache would be somehow a map from functions to results. This apparently would work, but this needs a way to give a unique identifier to each function (the key in the map), which I don’t know how to do! I’m thinking each function has a fixed address in the code, right, so that is a unique identifier? Am I correct? But what if the function is actually a “runtime-allocated/generated closure”, then this isn’t true anymore, because it gets shifted around by the gc? I guess I’m a bit confused because I don’t have a clear picture of how first-class functions are represented.