Today, I want to take a brief detour from our excursions into C# 2.0 and examine the C# 3.0 example from my recent article on higher-order functions:
The calculation being performed (summing the squares of the even numbers in an array) is not complicated, but I want to clarify that we don't actually have to define Filter, Map and Reduce in C# 3.0. While those names might be familiar to functional programmers, they already have equivalents in the .NET Framework 3.5.
Each of these are implemented as extension methods for IEnumerable<T>. So, we can rewrite the code like this:
The Aggregate method is a powerful way to create custom accumulations from an IEnumerable<T>. However, the .NET Framework 3.5 also provides several methods for common accumulations (e.g. Sum, Average, Count, Min, Max). In this situation, we could just use the Sum method.
Finally, C# 3.0 provides a natural way to express the Where and Select calls using a query expression.
While defining Filter, Map and Reduce are useful in C# 2.0, they are redundant in C# 3.0. We can use features already present instead of reinventing the wheel.
Have fun!
Page rendered at Tuesday, January 06, 2009 8:24:18 AM (Eastern Standard Time, UTC-05:00)