In the last entry, I wrote about an interesting discovery I made as I began to learn more about functional programming. In the first chapter of a book about the Ocaml language, I found a few lines the emphasized the ease and power of being able to supply functions as parameters to other functions (see code in last entry). I also mentioned how it was a little more cumbersome to implement in a language like C#, but not impossible. I didn't share that code, though, because I am a code tease. (Note: that's coDE tease. I don't want any getting the wrong impression.)
Can you pass in functions as parameters in C#? Sure you can, using delegates. In fact, when it comes to passing around these functions using delegates, the functions don't even have to be actual, named functions. (That's thanks to a new feature in C# 2.0, anonymous methods.) While you can definitely implement the same functional in C#, it looks a lot different.
public delegate T mydelegate(T x); public static void Main()
{
mydelegatesuccessor = delegate(int x) {return x + 1;};
mydelegatesquare = delegate(int x) {return x * x;};
Console.WriteLine(Compose(square, successor, 5));
}public static T Compose
(mydelegate method1, mydelegate method2, T x)
{
return method1(method2(x));
}
The code I just presented is the functional equivalent of the code presented in the last entry. Regardless of your expertise with either language, which one is easier to understand? Which would you rather write?
I'm a total C# dork, but I must say that I find the Ocaml/F# code easier to understand. Look how succint it is. Notice how it never once mentions anything about generics, or even data types. We don't need to create or understand a construct like a delegate in order to pass our functions around; we just pass them. That's very nice.
Posted by Cody at January 31, 2007 08:09 PM