I'm attempting to apply the memoization technique for Func<T1, T2, TResult>as described here but I cant seem to get the syntax right.
If I call Memoize<T1, T2> I end up retuing the Detuplify method.
Can someone tell me where I've gone wrong?
inteal static class ActionExtensions
{
public static Action<T> Memoize<T>(this Action<T> a)
{
// This doesn't prevent a(t) from being executed more than once for
// the same value (during the period while it is being calculated) but we can afford the overhead.
// The alteative is much more complicated involving multiple concurrent dictionaries and locking.
var cache = new ConcurrentDictionary<T, Action<T>>();
retu (t) => cache.GetOrAdd(t, a);
}
public static Action<T1, T2> Memoize<T1, T2>(this Action<T1, T2> a)
{
retu a.Tuplify().Memoize().Detuplify();
}
private static Action<Tuple<T1, T2>> Tuplify<T1, T2>(this Action<T1, T2> a)
{
retu t => a(t.Item1, t.Item2);
}
private static Action<T1, T2> Detuplify<T1, T2>(this Action<Tuple<T1, T2>> a)
{
retu (t1, t2) => a(Tuple.Create(t1, t2));
}
}
