Skip to content

Instantly share code, notes, and snippets.

@Vikaskumargd
Created July 1, 2017 18:35
Show Gist options
  • Save Vikaskumargd/221d3a873bf3ad1d2b71920c037f7369 to your computer and use it in GitHub Desktop.
Save Vikaskumargd/221d3a873bf3ad1d2b71920c037f7369 to your computer and use it in GitHub Desktop.
public static Func<A, R> Memoize<A, R>(this Func<A, R> f)
{
var map = new Dictionary<A, R>();
return a =>
{
R value;
if (map.TryGetValue(a, out value))
return value;
value = f(a);
map.Add(a, value);
return value;
};
}
@Vikaskumargd
Copy link
Author

Func<int, int> fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
fib = fib.Memoize();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment