Functional programming in C# 3.0 – (1)

I had a lot of fun to read Tomas Petricek’s article, “Concepts behind the C# 3.0 language“. Instead of listing all of the new syntax changes as most of other tutorials, Tomas shed some lights on the details about influence of the development of C# 3.0 from other languages, especially how Functional programming plays in C# 3.0. Actually, Lambda Expression and LINQ are really part of that.

So what is functional programming? Quote from Wikipedia:

Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast with the imperative programming style that emphasizes changes in state.[1]

So what it really tells us? I think the main point is “function is data” which means function can be use to be passed as an parameter or returned argument or modified as any other data in our application. Do we gain benefit for that? Sure, we do.

1. Functional programming can help model data operation. Here is the sample:

public static long Watch(Action act, T arg) 
{ 
        Stopwatch watch = new Stopwatch(); 
        watch.Start(); act(arg); 
        watch.Stop(); 
        return watch.ElapsedMilliseconds; 
}
 

This Watch function is totally decoupled with the Action, which could be “reading the data from database”, or “processing the data from a file”. It leads a clean design that Watch function and the Action function can be tested separately.

2. Parallel programming. If you have been worked on Multi-thread programming. You know how hard it is. The limitation of imperative language like C# focuses on the state change. But functional programming is passing function as argument as we mentioned above. The state actually is only closed in the function boundary. So there is no other thread can access that data. Microsoft has released PLINQ, a parallel programming add-on to current .NET framework 3.5. It will be a huge benefit for any .NET who will take advantage of multi-processor computers.

So far, so good, right? from next one, I will illustrate the functional programming features in C# 3.0. Definitely will show more code. Please stay tune.

Advertisements