lua-users home
lua-l archive

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


Microlight has a utility for the purpose.

> ml=require"ml"
> help(ml.memoize)
--- 'memoize' a function (cache returned value for next call).
-- This is useful if you have a function which is relatively expensive,
-- but you don't know in advance what values will be required, so
-- building a table upfront is wasteful/impossible.
-- @param func a function of at least one argument
-- @return a function with at least one argument, which is used as the key.


2013/10/30 Pierre Chapuis <catwell@archlinux.us>:
>> Doesn't memoization become very difficult, if at all possible, if you
>> don't have pure functions? Memoization works because you can assume that
>> if a function is called with the same arguments then it will give the same
>> results every time so we can remember the args -> result mapping. When you
>> have side-effects and mutable data it becomes very difficult. Which I
>> think makes it not very usable for Lua.
>
> Automatic memoization à la Haskell is not possible,
> but there is no reason why you could not have a way
> to memoize those functions you *know* are pure. It
> is an idiomatic way to do dynamic programming in Lua.
>
> If course if you apply it to a function that is *not*
> pure your program will be wrong. So the difference
> with a pure functional language is that the compiler
> will allow you to shoot yourself in the foot...
>
> --
> Pierre Chapuis
>
>