Skip to content

Instantly share code, notes, and snippets.

@isaacabraham
Last active December 22, 2015 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaacabraham/6538567 to your computer and use it in GitHub Desktop.
Save isaacabraham/6538567 to your computer and use it in GitHub Desktop.
Simple memoize function in C# along with client calling code.
// Raw Add method
public static int Add(Tuple<int, int> numbers)
{
return numbers.Item1 + numbers.Item2;
}
static void Main(string[] args)
{
// Memoized version of Add
var add = Memoize<Tuple<int, int>, int>(Add);
add(Tuple.Create(5, 10)); // Adding (5,10) to cache
add(Tuple.Create(5, 10)); // Cache hit for (5,10)
}
public static Func<TArg,TResult> Memoize<TArg, TResult>(Func<TArg, TResult> code)
{
var cache = new Dictionary<TArg, TResult>();
return (TArg input) =>
{
TResult result;
var resultIsCached = cache.TryGetValue(input, out result);
if (resultIsCached)
{
Console.WriteLine("Cache hit for {0}", input.ToString());
return result;
}
result = code(input);
Console.WriteLine("Adding {0} to cache", input.ToString());
cache[input] = result;
return result;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment