Skip to content

Instantly share code, notes, and snippets.

@jonpryor
Created November 5, 2012 15:02
Show Gist options
  • Save jonpryor/4017619 to your computer and use it in GitHub Desktop.
Save jonpryor/4017619 to your computer and use it in GitHub Desktop.
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