Category: Erlang
Up close and personal with Erlang
By Chee Ming on Sep 18, 2007 | In Exoweb, Erlang | 2 feedbacks »
I've been reading a bit about Erlang on the web and decided to take a plunge to learn it. I've been going through a few chapters of Joe Armstrong's Erlang book from the Pragmatic Programmers series and its been a pretty interesting mental ride. I've not really done much programming in functional languages except maybe a tiny bit of Lisp, so I am basically a newbie.
The variables in Erlang don't vary! Data types in Erlang are immutable. Which means a simple logic this, which is a very normal way of doing things in procedural languages, won't work:
i = 0
while i < 10
print i
i = i + 1
The pattern for Erlang would be to use arguments and tail recursion:
loop(Count) ->
if
Count < 10 ->
io:format("~w~n", [Count]),
loop(Count+1);
true ->
done
end.
But that isn't pretty, let me try again:
loop(Count) when Count < 10 ->
io:format("~w~n", [Count]),
loop(Count+1);
loop(_) ->
done.
There are probably many other ways to do it in Erlang that is more beautiful than what I've shown. What I want to emphasize is that its definitely a different way of solving problems.
One thing that I don't really agree with Erlang is the syntax. Erlang is full of punctuation. I think I've wasted quite a lot of brain cells just thinking of the right syntax rather than actually solving a particular problem. And I think it makes code harder to maintain. You can just copy and paste a code and fix the indentation. You need to worry about the commas, semicolon and periods. And at the end of a block you need to remember not to put any punctuation.
It is definitely tiring hunting down syntax errors. I'm too used to Python's whitespace and new lines, which I think is much more readable and maintainable.
I don't like the syntax but I do like the pattern matching features of the languages. They have a pretty interesting way to achieve polymorphism, which is normally overloading and overriding in object oriented languages. Check the following code out:
area({square, Side}) ->
Side * Side;
area({circle, Radius}) ->
3.142 * Radius * Radius;
area({triangle, A, B, C}) ->
S = (A + B + C)/2,
math:sqrt(S * (S - A) * (S - B) * (S - C));
area(Other) ->
{invalid_object, Other}.
And you would call the area() function in the following ways:
area({square, 2}).
area({circle, 3}).
area({triangle, 3, 4, 5}).
I'm just at the 5th chapter. Still 3 quarters more to go. I haven't started with the concurrency stuff which is where things start to get interesting with the language since it has that built in. Things should get pretty exciting. My plan is to build a system with Yaws and Mnesia. What should I build? I am not sure. I'll probably get some ideas along the way.
