Essentially, I was hoping there was a way to write an accumulate
method without needed to overload it.
You are not alone with this wish. Here's an related article on
codeproject and a feature request to ms:
http://www.codeproject.com/csharp/genericnumerics.asp
http://tinyurl.com/2pghky
Here's a sample showing how I worked around this to implement accumulate
in my port of the C++ STL (
www.codeplex.com/nstl):
using System.Collections.Generic;
namespace ConsoleApplication11
{
internal delegate Result
BinaryFunction<Arg1, Arg2, Result>(Arg1 lhs, Arg2 rhs);
static class Plus
{
public static BinaryFunction<int, int, int> Int32()
{
return delegate(int lhs, int rhs) { return lhs + rhs; };
}
public static BinaryFunction<string, string, string> String()
{
return delegate(string lhs, string rhs){return lhs + rhs; };
}
}
static class Algorithm
{
public static T
Accumulate<T>(IEnumerable<T> range, T init,
BinaryFunction<T, T, T> binaryOp)
{
foreach(T t in range)
init = binaryOp(init, t);
return init;
}
}
class Program
{
static void Main(string[] args)
{
IEnumerable<int> ints = new int[] {0, 1, 2, 3, 4, 5};
int zero = Algorithm.Accumulate(ints, -15, Plus.Int32());
}
}
}
HTH,
Andy