lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, May 14, 2008 at 6:40 PM, Norman Ramsey <nr@eecs.harvard.edu> wrote:
> I would be pleased if readers of this list could think of any improvements
> to the following memoize function:

Your code isn't testing for 'f' returning no values (which may or may
not be what you want).

I don't see why the 'update' closure is needed. Wouldn't it be more
straightforward to just say:

   function memoize (f)
      -- f must take at most one argument and return at most one result
      local cache = setmetatable({ }, { __mode = 'k' })
      return function (x, extra)
         assert(extra == nil) -- cache works with at most one arg
         local v = cache[x]
         if not v then
            v, extra = f(x)
            assert(extra == nil) -- cache works with at most one return value
            cache[x] = v
         end
         return v
      end
   end

Also, it's easy to allow f to return any number of values (unless
there's a reason you forbid that):

   function memoize (f)
      -- f must take at most one argument
      local cache = setmetatable({ }, { __mode = 'k' })
      return function (x, extra)
         assert(extra == nil) -- cache works with at most one arg
         local v = cache[x]
         if not v then
            v = { f(x) } -- save all return values
            cache[x] = v
         end
         return unpack(v)
      end
   end

Cheers,
Eric