Accumulate
前の記事の「delegate T AccumulateAction
完成版のAccumulateはこちら。
class Program
{
static void Main( string[] args )
{
int result = SumOfSquares( new int[] { 1, 2, 3, 4, 5 } );
Console.WriteLine( result );
Console.Read();
}delegate T Combiner<T>( T x, T y );
static T Accumulate<T>( Combiner<T> combiner, T nullValue, IEnumerator<T> it )
{
if ( !it.MoveNext() )
return nullValue;
return combiner( it.Current, Accumulate<T>( combiner, nullValue, it ) );
}static int SumOfSquares( IEnumerable<int> list )
{
return Accumulate( delegate( int x, int y ) { return x * x + y; }, 0, list.GetEnumerator() );
}
}