Memoizing a function using only a subset of arguments as an identifier

Aleksandr_Mikheev
Mon, 11 Dec 2023 10:38:03 +0000
General Usage

Suppose I have a function of two arguments. For instance,

function foo(a::Float64,b::Float64)
   return a^2 - b
end

Is it possible to memoize it based on the first argument only? I understand how I can partially achieve this goal:

using Memoization

function foo(b::Float64)
   @memoize function f(a::Float64)
      return a^2 - b
   end
end

Now I can just define g1 = foo(1.0), g2 = foo(2.0), etc. But it seems there should be a more elegant way to get what I want, such that I don’t need to define a new function for every ‘dummy’ argument.

Also, just as a reference, here’s the stackoverflow thread that covers exactly the same question, albeit in Python.

P.S. I am well aware that what my foo returns depends on b, so it seems odd to memoize it this way, etc. This is just a stupid example that is not meant to be taken seriously.

4 posts - 2 participants