Memoization is a useful thing and since it's heavily related to functions, I'd assume Haskell has the right machinery to implement it in an at least fairly straightforward manner.
var memo = function (f) {
var cache = {};
return function (x) {
if (cache[x]) return cache[x];
else return cache[x] = f(x);
}
}
//Usage:
var fib = memo(function (x) {
if (x == 0) return 1;
if (x == 1) return 1;
return fib(x - 1) + fib(x - 2);
});
fib(100);
This is the code I wrote in JavaScript that does what I want. What would be a good translation to Haskell that can offer similar practicality AND performance?
To reduce ambiguity of the question, I'm not interested in replicating the generality of the JS solution because Haskell is strongly typed. Something with a type signature of
memo :: (Int -> b) -> (Int -> b)
that can be manually extended for multiple parameters and maybe even various types would be fine.