Skip to content

Instantly share code, notes, and snippets.

@mndrake
Last active January 4, 2016 06:39
Show Gist options
  • Save mndrake/8583578 to your computer and use it in GitHub Desktop.
Save mndrake/8583578 to your computer and use it in GitHub Desktop.
namespace Utility
{
using System;
using System.Collections.Generic;
// based on:
//http://stackoverflow.com/questions/2852161/c-sharp-memoization-of-functions-with-arbitrary-number-of-arguments
public static class Memoizer
{
// single input memoize
public static Func<A, R> Memoize<A, R>(this Func<A, R> f)
{
var cache = new Dictionary<A, R>();
return a =>
{
R r;
if (!cache.TryGetValue(a, out r))
{
r = f(a);
cache.Add(a, r);
}
return r;
};
}
// two input memoize
public static Func<A, B, R> Memoize<A, B, R>(this Func<A, B, R> f)
{
Func<Tuple<A, B>, R> tuplified = t => f(t.Item1, t.Item2);
Func<Tuple<A, B>, R> memoized = tuplified.Memoize();
return (a, b) => memoized(Tuple.Create(a, b));
}
// three input memoize
public static Func<A, B, C, R> Memoize<A, B, C, R>(this Func<A, B, C, R> f)
{
Func<Tuple<A, B, C>, R> tuplified = t => f(t.Item1, t.Item2, t.Item3);
Func<Tuple<A, B, C>, R> memoized = tuplified.Memoize();
return (a, b, c) => memoized(Tuple.Create(a, b, c));
}
// four input memoize
public static Func<A, B, C, D, R> Memoize<A, B, C, D, R>(this Func<A, B, C, D, R> f)
{
Func<Tuple<A, B, C, D>, R> tuplified = t => f(t.Item1, t.Item2, t.Item3, t.Item4);
Func<Tuple<A, B, C, D>, R> memoized = tuplified.Memoize();
return (a, b, c, d) => memoized(Tuple.Create(a, b, c, d));
}
}
public class MemoizerExample
{
// --- original non-cached version
// function that we want to cache the results
public static double SlowAdd(double x, double y)
{
System.Threading.Thread.Sleep(5000);
return x + y;
}
// --- memoized version
// private memoized version of the function
private Func<double, double, double> MemoizedSlowAdd =
Memoizer.Memoize((double x, double y) =>
{
System.Threading.Thread.Sleep(5000);
return x + y;
}
);
// the new cached version of the original slow function
public double CachedSlowAdd(double x, double y)
{
return MemoizedSlowAdd(x, y);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment