C# Memoization of functions with arbitrary number of arguments [closed]

How about this? First write a one-argument memoizer: static Func<A, R> Memoize<A, R>(this Func<A, R> f) { var d = new Dictionary<A, R>(); return a=> { R r; if (!d.TryGetValue(a, out r)) { r = f(a); d.Add(a, r); } return r; }; } Straightforward. Now write a function tuplifier: static Func<Tuple<A, B>, R> Tuplify<A, B, … Read more

Which Ruby memoize pattern does ActiveSupport::Memoizable refer to?

Here is the commit (and subsequent discussion) where Memoizable was deprecated: https://github.com/rails/rails/commit/36253916b0b788d6ded56669d37c96ed05c92c5c The author advocates the @foo ||= … approach and points to this commit as an example for migration: https://github.com/rails/rails/commit/f2c0fb32c0dce7f8da0ce446e2d2f0cba5fd44b3. Edit: Note that I don’t necessarily interpret this change as meaning that all instances of memoize can or should be replaced w/ this pattern. … Read more

memoize to disk – python – persistent memoization

Python offers a very elegant way to do this – decorators. Basically, a decorator is a function that wraps another function to provide additional functionality without changing the function source code. Your decorator can be written like this: import json def persist_to_file(file_name): def decorator(original_func): try: cache = json.load(open(file_name, ‘r’)) except (IOError, ValueError): cache = {} … Read more

Writing Universal memoization function in C++11

A compact one returning a lambda: template <typename R, typename… Args> std::function<R (Args…)> memo(R (*fn)(Args…)) { std::map<std::tuple<Args…>, R> table; return [fn, table](Args… args) mutable -> R { auto argt = std::make_tuple(args…); auto memoized = table.find(argt); if(memoized == table.end()) { auto result = fn(args…); table[argt] = result; return result; } else { return memoized->second; } }; … Read more

What’s the difference between recursion, memoization & dynamic programming? [duplicate]

Consider calculating the fibonacci sequence: Pure recursion: int fib(int x) { if (x < 2) return 1; return fib(x-1) + fib(x-2); } results in exponential number of calls. Recursion with memoization/DP: int fib(int x) { static vector<int> cache(N, -1); int& result = cache[x]; if (result == -1) { if (x < 2) result = 1; … Read more