Accumulate

前の記事の「delegate T AccumulateAction( Combiner combiner, T value, IEnumerator it );」が不要なことに今さら気付いた。昨日の問題は引っ掛け問題っぽくなってしまってるw 問題のほうは訂正しとこ。
完成版の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() );
}
}