Generic memoization method (C#)

Posted on

Func<T, R> Memoize<T, R>(Func<T, R> func)
{
    var cache = new Dictionary<T, R>();
    return arg =>
    {
        R result;
        if (cache.TryGetValue(arg, out result))
            return result;

        result = func(arg);
        cache.Add(arg, result);

        return result;
    };
}

void Test()
{
    var powerMem = Memoize<int, int>(a =>
    {
        Console.WriteLine("{0}^2 is {1}", a, a * a);
        return a*a;
    });

    powerMem(1); // Wypisze tylko teraz na konsole
    powerMem(1);
}

void Test2()
{
    var addMem = Memoize((Tuple<int, int> arg) =>
    {
        Console.WriteLine("adding {0} + {1}; ", arg.Item1, arg.Item2);
        return arg.Item1 + arg.Item2;
    });

    addMem(Tuple.Create(1, 2)); // Wypisze tylko teraz na konsole
    addMem(Tuple.Create(1, 2));
}

Z książki Real-World Functional Programming rozdział 10.4.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s