lua-users home
lua-l archive

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


2013/12/14 Sir Pogsalot <sir.pogsalot@gmail.com>:

> Writing this because I have seen a lot of inflexible attempts at memoizing
> function calls out there. :>

The problem is interesting but undetermined, and I've just seen another
inflexible attempt. :>

Memoizing implies that the function should always return the
same values given the same arguments.

Now, suppose I have a simple function that merely counts the number
of values in a table.

> count = function(t) local n=0 for k in next,t do n=n+1 end return n end
> f = memoize(count)
> print(f(math))
30

Next time I ask for f(math), do I want 30 again — in which case I definitely
don't want to serialize `math` — or do I want to know how many items
are actually in `math` then — in which case, why should I memoize?

Don't be distracted by the triviality of this example. In real life,
the argument
will be someone's object complete with obfuscated metatable.

That's why memoizing tends to be inflexible, and why the simplest and
most inflexible solution of all (this version is by Steve Donovan):

function ml.memoize(func)
    return setmetatable({}, {
        __index = function(self, k, ...)
            local v = func(k,...)
            self[k] = v
            return v
        end,
        __call = function(self, k) return self[k] end
    })
end

is IMHO the only useful way to do it.