I'm writing a function to find triangle numbers and the natural way to write it is recursively:
function triangle (x)
if x == 0 then return 0 end
return x+triangle(x-1)
end
But attempting to calculate the first 100,000 triangle numbers fails with a stack overflow after a while. This is an ideal function to memoize, but I want a solution that will memoize any function I pass to it.
See this blog post for a generic Scala solution, up to 4 arguments.
In C# 3.0 - for recursive functions, you can do something like:
Then you can create a memoized Fibonacci function like this:
Recursion isn't necessary. The nth triangle number is n(n-1)/2, so...
In Perl generic memoization is easy to get. The Memoize module is part of the perl core and is highly reliable, flexible, and easy-to-use.
The example from it's manpage:
You can add, remove, and customize memoization of functions at run time! You can provide callbacks for custom memento computation.
Memoize.pm even has facilities for making the memento cache persistent, so it does not need to be re-filled on each invocation of your program!
Here's the documentation: http://perldoc.perl.org/5.8.8/Memoize.html
Here is a generic C# 3.0 implementation, if it could help :
(Quoted from a french blog article)
In Scala (untested):
Note that this only works for functions of arity 1, but with currying you could make it work. The more subtle problem is that
memoize(f) != memoize(f)
for any functionf
. One very sneaky way to fix this would be something like the following:I don't think that this will compile, but it does illustrate the idea.