Tuesday, February 1, 2011

INumeric policy.

Policies:
interface INumericPolicy<T>
{
    T Zero();
    T Add(T a, T b);
    ...
}

class All: INumericPolicy<int>, INumericPolicy<long>, ...
{
    ...
    public static All P = new All();
}
User's algorithms:
static class Algorithms
{
    public static T Sum<P, T>(this P p, params T[] a)
        where P: INumericPolicy<T>
    {
        var r = p.Zero();
        foreach(var i in a)
        {
            r = p.Add(r, i);
        }
        return r;
    }

    ...
}
Usage:
int i = All.P.Sum(1, 2, 3, 4, 5);
long l = All.P.Sum(1L, 2, 3, 4, 5);

No comments:

Post a Comment