Wednesday, June 28, 2006

Erlang

I had a little look at Erlang over the weekend. I was inspired by some articles on defmacro.org which I found through del.icio.us.
I've not done functional programming since Uni (apart from some XSLT, and that required some deep thought), and I don't think I really appreciated it at the time.
I'm not converted (yet), but there are a few concepts that I really like.
For example, I was debugging a (non-functional) program yesterday. Essentially, it was calling various functions (in some cases recursively) to build up a string. All these functions changed class level variables, rather than each function returning the bits to add onto the string.
The debugging was complicated because I had to step through each function because any function could append something to the class level variable.
It wasn't pretty. (I count this abuse of class variables - basically using them as global variables.)
What would have been better is if the functions returned the string to append to the class level variable, and one controlling function dealt with this.
So, instead of this:

var importantString = '';
function a(i) {
if ( i < 10 ) {
importantString += '' + i;
b(i);
}
}

function b(i) {
importantString += ',';
a ( i + i );
}
it should be this:
function a ( i ) {
if ( i < 10 )
return '' + i + b(i);
}
}


function b (i) {
return ',' + a(i);
}
I realise this is a trival example, but by eliminating the global variable, it makes it a lot easier to find problems, and to test. For example, we can expect a(1) to always return '1' + whatever b(1) returns - if we replace b with a mock version, then we can test it really easily. Similarly, testing b become equally as easy.
In Erlang, variables are immutable so we cannot recreate the first version The second version (easier to test, easier to debug) , therefore, becomes the way to do things.
I'm not saying you can't write some terrible code in Erlang, or with functional programming, but I wanted to demonstrate how features in one language can be usefull constructs in other languages.

No comments: