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

Memoization in Haskell?

We can do this very efficiently by making a structure that we can index in sub-linear time. But first, {-# LANGUAGE BangPatterns #-} import Data.Function (fix) Let’s define f, but make it use ‘open recursion’ rather than call itself directly. f :: (Int -> Int) -> Int -> Int f mf 0 = 0 f … Read more

What is the difference between memoization and dynamic programming?

Relevant article on Programming.Guide: Dynamic programming vs memoization vs tabulation What is difference between memoization and dynamic programming? Memoization is a term describing an optimization technique where you cache previously computed results, and return the cached result when the same computation is needed again. Dynamic programming is a technique for solving problems of recursive nature, … Read more

What is the difference between bottom-up and top-down?

rev4: A very eloquent comment by user Sammaron has noted that, perhaps, this answer previously confused top-down and bottom-up. While originally this answer (rev3) and other answers said that “bottom-up is memoization” (“assume the subproblems”), it may be the inverse (that is, “top-down” may be “assume the subproblems” and “bottom-up” may be “compose the subproblems”). … Read more

Is there a decorator to simply cache function return values?

Starting from Python 3.2 there is a built-in decorator: @functools.lru_cache(maxsize=100, typed=False) Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments. Example of an LRU cache for computing Fibonacci … Read more