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, February 09, 2010 9:59:43 AM (Eastern Standard Time, UTC-05:00)
If you're interested in learning F#, this is the most comprehensive book available. The text is well written and the examples are instructive. And after all, the author is the inventor of F#.
Because this book provides source code in Standard ML, it's a fantastic resource for learning F#. One bit of warning: this book does not teach classic data structures. While structures such as binomial heaps and red-black trees are presented, it is assumed that the reader already knows and understands them.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.