Created
November 5, 2012 15:02
-
-
Save jonpryor/4017619 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Memoization<T, TResult> { | |
internal Memoization (Func<T, TResult> f, IDictionary<T, TResult> d) | |
{ | |
Invoke = f; | |
Values = d; | |
} | |
public Func<TResult> Invoke {get; private set;} | |
public IDictionary<T, TResult> Values {get; private set;} | |
} | |
static class FuncCoda { | |
public static Memoization<T, TResult> Memoize (this Func<T, TResult> self, IDictionary<T, TResult> cache = null) | |
{ | |
cache = cache ?? new ConcurrentDictionary<T, TResult>(); | |
Func<T, TResult> c = v => { | |
TResult r; | |
if (cache.TryGetValue (v, out r)) | |
return r; | |
cache.Add (v, r = self (v)); | |
return r; | |
}; | |
return new Memoization<T, TResult>(c, cache); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment