Search code examples
c#genericsmemoization

Which type signature can be used to memoize a generic method in C#?


I have a memoization function 'Memo' and I want to pass generic method 'Foo' to it as a delegate, which type signature can I use to achieve this?

public static class Program
{

    private static Func<int, int> Foo(int n)
    {
        return (int x) =>
        {
            if (n <= 2) return x;
            return Foo(n - 1)(1) + Foo(n - 2)(1);
        };
    } 

    private static Func<A, B> Memo<A, B>(Func<A, B> f)
    {
    var cache = new Dictionary<A, B>();
        return (A a) =>
    {
        if (cache.ContainsKey(a))
        {
            return cache[a];
        }
        var b = f(a);
        cache[a] = b;
        return b;
    }; 
}

Solution

  • Methods are implicitly convertible to an Action / Func that matches their signature, so you can do this:

    Func<int, Func<int, int>> foo = Foo;
    Memo(foo);
    

    Now that foo has a type, the generic arguments of Memo can be inferred.