title: Weak-memoizing result of multi-parameter function in OCaml
body: <p>I am looking for a way to memoize the results of an OCaml function <code>f</code> that takes two parameters (or more, in general). In addition (and this is the difficult part), I want the map underlying this process to forget a result altogether if either of the values for the two parameters is garbage collected.</p>
  
  <p>For a function that takes exactly one argument, this can be done with the <code>Weak</code> module and its <code>Make</code> functor in a straightforward way. To generalise this to something that can memoize functions of higher arity, a naive solution is to create a weak map from tuples of values to  result values. But this will not work correctly with respect to garbage collection, as the tuple of values only exists within the scope of the memoization function, not the client code that calls <code>f</code>. In fact, the weak reference will be to the tuple, which is going to be garbage collected right after memoization (in the worst case).</p>
  
  <p>Is there a way to do this without re-implementing <code>Weak.Make</code>?</p>
  
  <p>Hash-consing is orthogonal to my requirements and is, in fact, not really desirable for my values.</p>
  
  <p>Thanks!</p>