Saturday, December 01, 2007

At my DevTeach presentation I showed how you can do Map and Filter from Functional programming right now in C# 2.0. In mathematics Reduce is "the process of manipulating a series of equations or matrices into a desired 'simpler' format". In C# you can think of it as taking a list and reducing it down to one value. 

Here is my implementation of Reduce in C# 2.0:

[Test]
public void ShouldReduceListOfIntegersToTotal()
{
    IList<int> numbers = new List<int>();
    numbers.Add(1);
    numbers.Add(2);
    numbers.Add(3);
    numbers.Add(4);
 
    RecordBook<int> recordBook = new RecordBook<int>(numbers);
 
    Assert.AreEqual(10, recordBook.Reduce<int, int>(numbers, Add));
}
 
[Test]
public void ShouldPrintIntegersAsOneString()
{
    IList<int> numbers = new List<int>();
    numbers.Add(1);
    numbers.Add(2);
    numbers.Add(3);
    numbers.Add(4);
 
    RecordBook<int> recordBook = new RecordBook<int>(numbers);
 
    Assert.AreEqual("1234", recordBook.Reduce<int, string>(numbers, BuildStringFromIntegers));
}
 
private string BuildStringFromIntegers(int number, string test)
{
    return test + number;
}
 
private int Add(int number1, int number2)
{
    return number1 + number2;
}

and the implementation of the tests:

public delegate TResult Accumulator<TSource, TResult>(TSource x, TResult y);
 
public TResult Reduce<TSource, TResult>(IList<TSource> source, Accumulator<TSource, TResult> accumulator)
{
    TResult result = default(TResult);
 
    foreach (TSource item in source)
        result = accumulator(item, result);
 
    return result;
}

The first test calculates the sum of adding all the integers in the list together using the add function. The second test takes an integer and concatenates it to a string producing a string of all the integers in the list.

The Reduce function introduces the default keyword that you can leverage with generics. This will give you the default value for value types (0 for integers, 0.0 for decimals, null for string).

Saturday, December 01, 2007 1:21:02 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]  | 

Theme design by Jelle Druyts

Pick a theme: