Last active
December 22, 2015 22:09
-
-
Save isaacabraham/6538567 to your computer and use it in GitHub Desktop.
Simple memoize function in C# along with client calling code.
This file contains 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
// 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) | |
} |
This file contains 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
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