What type to use to store an in-memory mutable data table in Scala?

You could use a mutable.Map[TupleN[A1, A2, …, AN], R] , or if memory is a concern, a WeakHashMap[1]. The definitions below (built on the memoization code from michid’s blog) allow you to easily memoize functions with multiple arguments. For example: import Memoize._ def reallySlowFn(i: Int, s: String): Int = { Thread.sleep(3000) i + s.length } … Read more

Caching class attributes in Python

3.8 ≤ Python @property and @functools.lru_cache have been combined into @cached_property. import functools class MyClass: @functools.cached_property def foo(self): print(“long calculation here”) return 21 * 2 3.2 ≤ Python < 3.8 You should use both @property and @functools.lru_cache decorators: import functools class MyClass: @property @functools.lru_cache() def foo(self): print(“long calculation here”) return 21 * 2 This answer … 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

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