Created
January 19, 2011 17:42
-
-
Save ahjohannessen/786524 to your computer and use it in GitHub Desktop.
Memoization
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 class Memoization | |
{ | |
public static Func<TA, TR> Memoize<TA, TR>(Func<TA, TR> f) | |
{ | |
var map = new Dictionary<TA, TR>(); | |
return a => | |
{ | |
lock (map) | |
{ | |
TR value; | |
if (map.TryGetValue(a, out value)) | |
{ | |
return value; | |
} | |
value = f(a); | |
map.Add(a, value); | |
return value; | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment