October 23, 2009

Hello World in Erlang

Before you star reading, caution, ERLANG i highly vicious and can cause you to hate any other programming languages you are used to.

Install Erlang

apt-get install erlang

now lets start with the most simple code you can write in erlang

Save it as hello.erl and run erlang shell

erl

Now you can compile hello.erl from the erlang shell. Don’t forget the full-stop (”period” in American English) at the end of each command. After you just need to execute Module:Function().


Erlang R13B01 (erts-5.7.2) [source] [rq:1] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.7.2 (abort with ^G)
1> c(hello).
{ok,hello}
2>hello:start().
Hello, World!ok
3>

Now that that you are not long afraid of erlang, lets show some of the mighty power everybody talks about, and build “hello world elang style” ;)

copy the code above

now compile the code, and execute the following commands


Erlang R13B (erts-5.7.1) [source] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.1 (abort with ^G)
1> c(hello2).
{ok,hello2}
2> Pid = hello2:start().
<0.39.0>
3> Pid ! hello.
Hello, World!
hello
4> Pid ! goodbye.
goodbye
5> Pid ! hello.
hello
6>

In resume what you have just did, was create a new process with a process id = Pid, that will be waiting for messages. When it receives the message hello, it prints Hello World, and it calls itself to continue listening, when you send the message goodbye the process just finishes execution and dye.

All this with just a few lines of code, and a very simple syntax :) , but this is just the beginning, now imagine that this process can be running in any machine in the world, and you still can use exactly the same code! This and much more WOW effects is what makes erlang so amazing.

Now in order to really learn erlang i recommend you to get Joe Armstrong the erlang creator,
Programming Erlang: Software for a Concurrent World book and visit the erlang best documentation repo http://erlang.org/doc/

Please check also the source and inspiration for this post.

blog comments powered by Disqus