試してみよう

Joelの試してみようの1問目のC#版。


1c#.(C#2.0) 次の問題は1bをC#2.0にしたものだ。

次のメソッド


[]delegate[] T Combiner<T>( T x, T y );

static T Accumulate<T>( Combiner<T> combiner, T nullValue, Queue<T> q )
{
if ( q.Count == 0 )
return nullValue;
T first = q.Dequeue();
return combiner( first, Accumulate<T>( combiner, nullValue, q ) );
}

を用い、リストの平方和を求めるSumOfSquaresを実装せよ。例:


SumOfSquares( new Queue<int>( new int[] { 1, 2, 3, 4, 5 } ) );

の値は55になる。

(答えを見るには、箱の中のテキストを選択する。)


static int SumOfSquares( Queue q )
{
    return Accumulate( delegate( int x, int y ) { return x * x + y; }, 0, q );
}