Skip to content

Instantly share code, notes, and snippets.

@meklarian
Forked from dvdsgl/CachedFunc.cs
Created February 14, 2013 00:58
Show Gist options
  • Save meklarian/4949806 to your computer and use it in GitHub Desktop.
Save meklarian/4949806 to your computer and use it in GitHub Desktop.
// Quickly create Funcs that memoize expensive computations.
//
// In this example, ExpensiveMethod is only called once!
//
// var cached = CachedFunc.Make ((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> Make<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> Make<A, B, C> (Func<A, B, C> f)
{
var fTupled = Make<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> Make<A, B, C, D> (Func<A, B, C, D> f)
{
var fTupled = Make<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