I’ve just recently discovered the functional programming style and I’m convinced that it will reduce development efforts, make code easier to read, make software more maintainable. However, the problem is I sucked at convincing anyone.
Well, recently I was given a chance to give a talk on how to reduce software development and maintenance efforts, and I wanted to introduce them the concept of functional programming and how it benefit the team. I had this idea of showing people 2 set of code that does exactly the same thing, one coded in a very imperative way, and the other in a very functional way, to show that functional programming can made code way shorter, easier to understand and thus maintainable. Is there such an example, beside the famous sum of squares example by Luca Bolognese?
If you’ve only just discovered functional programming, I do not recommend trying to speak authoritatively on the subject. I know for the first 6 months while I was learnig F#, all of my code was just C# with a little more awkward syntax. However, after that period of time, I was able to write consistently good code in an idiomatic, functional style.
I recommend that you do the same: wait for 6 months or so until functional programming style comes more naturally, then give your presentation.
I gave an F# presentation to the .NET users group in my area, and many people in my group were impressed by F#’s pattern matching. Specifically, I showed how to traverse an abstract syntax tree in C# and F#:
The code above is written in an idiomatic C# style. It uses the visitor pattern rather than type-testing to guarantee type safety. This is about 218 LOC.
Here’s the F# version:
This is 65 LOC. Since it uses pattern matching rather than the visitor pattern, we don’t lose any type-safety, and the code is very easy to read.
Any kind of symbolic processing is orders of magnitude easier to write in F# than C#.
[Edit to add:] Oh, and pattern matching isn’t just a replacement for the visitor pattern, it also allows you to match against the shape of data. For example, here’s a function which converts Nand’s to their equivalents:
Its not possible to write this code concisely at all in C#.