Why should we use functional programming: a simple example

Good evening,

I’m just taking the time to add more content on functional programming. When I talk about this paradigm with programmers who haven’t had the time to work with it, they always tell me that the code is difficult to understand and that it would be difficult to maintain. I would like to show a simple example which shows that this statement is wrong.

Because I would agree that if you work in an environment where nobody works in F# it is not very likely that you will switch programming technology, I will use C# for my example. Indeed, C# supports some functional programming features as discussed in this book:

Functional Programming in C#: Classic Programming Techniques for Modern Projects (Wrox Programmer to Programmer)

I will take a simple example to demonstrate why functional programming can actually be much simpler to read and help developers avoid making mistakes. Let’s assume you have a list of integers and that you want to get the sum of the squares of the elements of the list.

In imperative programming (the paradigm used normally in C#) you would proceed as follows:

int[] myList = new int[] {1,2,3};

double res=0;
for (int i=0; i<3; i++)
{
   res+=Math.Pow(myList[i],2);
}

return res;

As you can see, it takes about 6 lines (with clear formatting) because you have to setup a result variable, and the you have to make sure that this variable is implemented by the square of each number. You also need to see that you don’t make any mistake in the definition of the loop as it depends on the length of the list.

Now, let’s see how you can do exactly the same thing using functional programming:

int[] myList = new int[] {1,2,3};

return myList.Select(x=>Math.Pow(x,2)).Sum();

As a matter of fact, you can see that the “algorithm” is much shorter there is no problem considering the length of the list or setting up a return variable. I also believe that the code is easier to read, because you do not have to tell the program everything it has to do, you just explain the logic and the actual implementation happens in the background.

That’s it for today,

See you next time!