Skip to content

Instantly share code, notes, and snippets.

@dvdsgl
Last active December 13, 2015 17:38
Show Gist options
  • Save dvdsgl/4949714 to your computer and use it in GitHub Desktop.
Save dvdsgl/4949714 to your computer and use it in GitHub Desktop.
Quickly create Funcs that memoize expensive computations.
// Quickly create Funcs that memoize expensive computations.
//
// In this example, ExpensiveMethod is only called once!
//
// var cached = CachedFunc.Create ((int x, string y) => x + ExpensiveMethod (y));
// for (int i = 0; i < 1000; i++)
// cached (123, "hello");
public static class CachedFunc
{
public static Func<A, B> Create<A, B> (Func<A, B> f)
{
var cache = new Dictionary<A, B> ();
return a => cache.ContainsKey (a) ? cache[a] : cache[a] = f (a);
}
public static Func<A, B, C> Create<A, B, C> (Func<A, B, C> f)
{
var fTupled = Create<Tuple<A, B>, C> (tuple => f (tuple.Item1, tuple.Item2));
return (a, b) => fTupled (Tuple.Create (a, b));
}
public static Func<A, B, C, D> Create<A, B, C, D> (Func<A, B, C, D> f)
{
var fTupled = Create<Tuple<A, B, C>, D> (tuple => f (tuple.Item1, tuple.Item2, tuple.Item3));
return (a, b, c) => fTupled (Tuple.Create (a, b, c));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment