Archive for the ‘Learning Erlang’ Category

Learning Erlang: The Beautiful Quicksort

Sometimes you really have to stop and contemplate how beautiful code is. This is an erlang quicksort algorithm, one of the most efficient (if I remember correctly it’s the most efficient) sorting algorithms. I still remember the pains of implementing it in C.

qsort([]) -> [];
qsort([Pivot|T]) ->
	qsort([X || X <- T, X =< Pivot])
	++ [Pivot] ++
	qsort([X || X <- T, X > Pivot]).

Short + Clean + Elegant = Beautiful.

Learning Erlang, day 1: No Variables?

I first heard of Erlang from SamePlace creator, Massimiliano Mirra. He mostly praised the functional nature of the language and its performance.

I always listen to my friends, so I made a mental note, and every once in a while I tried to start with Erlang, but other stuff(tm) always got the priority.

A few days ago, generating a burst of blog posts, the Pragmatic Programmers released the beta version of Programming Erlang. This was not a coincidence. When both Massimiliano and the Pragmatic Programmers suggest you should learn a new language you better do it, and be happy :)

So I went to the pragprog website and looked through the table of contents. It was really interesting and I bought the beta book.

Yesterday I got my hands wet with erlangness for the first time and decided to create a new category of posts, Learning Erlang, that will be filled with my observation about my efforts to learn a functional language after all these years of object orientedness.

The first thing you will notice when working with erlang is that there are no variables. Ok, stop, don’t close the browser, it’s not entirely true, there are variables, but you can assign them only once.

To better explain how erlang treats variables I’ll show you a snippet taken from the erlang interactive interpreter, erl:

Eshell V5.5.3  (abort with ^G)
1> X = 45.
45
2> X.
45
3> X = 23.
	

=ERROR REPORT==== 15-Mar-2007::09:55:53 ===
Error in process <0.29.0> with exit value: {{badmatch,23},[{erl_eval,expr,3}]}

  • exited: {{badmatch,23},[{erl_eval,expr,3}]} ** 4> X = 45. 45

Line 1 just assigns the X variable (in erlang variables start with a capital letter, and statements end with a period). What erlang really does here is matching X with 45. It notices that X is unbound and does whatever it can to make the statement true, so it binds X to 45. In line 2 we just check what X is bound to. In line 3 we learn how erlang works by trying to match X (now 45) to 23. Boom! nasty error for us. Being very scared, in line 4 we try to match X to 45, just in case, and we notice erlang likes that statement.

I promise that once you get used to this way of handling variables it doesn’t look so strange anymore :)