May 19, 2010

Functional aspect of c#

Two generic delegate in c#, makes c# look more like a functional language, they are Action<T>, Func<T1, T2, ...>. The functional feature let you easily express your algorithm, without using the traditional design pattern. These delegates can be compared with function in javascript, and lamda in other language. For example,


interface IStrategy
{
   void Execute(object o);
}

Using design pattern, we have to write a more code to aggregate different strategies. But using Action<T> is more succinct.


Action<object> oldAction = ... ;//
Action<object> newAction = (o) => { Console.Write("preAction"); oldAction(o); Console.Write("postAction"); }
newAction(o);

If we want to go a step further, we can use function(lamda, delegate) to create functions. For example:


Func<Action<object>, Action<object>> createFunc = (func) => 
{
   return (o) => { 
             Console.Write("preAction"); 
             func(o); 
             Console.Write("postAction"); 
          };
}

Action<ojbect> newAction = createFunc(oldAction);
newAction(o);

Functional language is not new, Javascript is a functional language, and it has been doing this for a long long time. The power functional programming is that you can easily define new function easily, so that you can get interesting result of the new function.