Thursday, 15 March 2007

What Would a Functional Progammer Do?

As C# adopts features from functional programming languages it is becoming increasingly possible to program in an-least partially functional style as part of your day-job.

At time of writing I am using C# 2.0, which has reasonable support for lambda functions in the form of delegates, but they are ugly, because of the presence of strict-typing / absence of type-inference. You need to think things out functionally and then translate into the clunky C# 2.0 notation.

Things will get better with C# 3.0 and a host of functional-inspired features, including limited-type inference and cleaner notation to support LINQ.

Anyway, yesterday I was pairing with a colleague working on implementing some experimental enhancements to some core algorithms, and we were running into difficulties. Because the implementation was in C# we were thinking in an imperative way, and after running through a few options and hitting various dead-ends I asked Peter, "What would a functional programmer do?"

We were working on variations of an in-place algorithm, where a functional programmer would tend to write -- wait for it! -- a pure function. In our case a more functional approach was going to be a lot easier. Our context had blinkered us. And once you take a step back and put the functional hat on, other avenues open up.

So, here's a short list of things a functional programmer might do, and which are worth thinking about when you're trying to solve a programming problem:
  1. In-place modification or pure function?
  2. Higher-order functions: Does treating code as data lead to simplifications?
  3. Can monads help?
Of course the amount that you can do may depend on language support that is present. Item 5 is a reminder to get on top of the monads concept: "If you can't understand it, you won't recognize when you can use it!"

All of this is in aid of the ideals of better abstractions, clearer and more understandable code, leading to higher quality and greater satisfaction and success.

There's a paradox that one may need greater understanding to express things more simply, and that for someone with less understanding the higher. clearer expression may be incomprehensible. But that's really old news: Look at the history of science and mathematics. Example: Want to know the area under a funny looking curve? Easy if you know calculus. Don't know calculus? A simple explanation may be hard to come by!

Now for the big question:

If Jesus were alive today, would he use a functional programming language? Who knows?

But Moses would, for sure.

No comments: