I had to cache the results a couple methods recently, and only after I had done it a few times, I realized I should just write a memoization extension for System.Func.
public static Func<T, TResult> Memoize<T, TResult>(this Func<T, TResult> func) { Dictionary<T, TResult> dict = new Dictionary<T, TResult>(); return input => { if (!dict.ContainsKey(input)) { dict[input] = func(input); } return dict[input]; }; } |
With this handy extension, I'm free to have fun with memoizing arbitrary Funcs.
Func<int, int> fib = n => { int a = 0; int b = 1; for (int i = 0; i < n; i++) { int temp = a; a = b; b = temp + b; } return a; }; Func<int, int> memoizedFib = fib.Memoize(); |