Thursday, October 11, 2007

Day2: ERLANG - The language

1. The Hello World in ERLANG

From the era of "C", all text books start with the infamous "HelloWorld" program. I said "infamous", i really mean it, because it stresses on "printf" and almost all the kids from colleges/universities believe C is all about printf and scanf. I know it is debatable. But this blog stresses on ERLANG.

So the HelloWorld equivalent in ERLANG is below.

-module(fact).
-export([fac/1]).


fac(0) ->
1;

fac(N) when N > 0 ->
N * fac(N-1).


If the power of "C" is in "printf" (just kidding), the power of ERLANG is in recursion. The above snippet can be read as two clauses

Clause 1: Factorial of Zero is 1

Clause 2: Factorial of a number N is N times factorial of (N-1) when N is greater than ZERO.

Yes, the language simply accepts the clauses as it is.

The fist two lines tells the ERLANG runtime, that it is a ERLANG module named "fact" and the module exports a function called "fac" which takes one parameter.

2. How it differs from other popular programming languages like C, PASCAL etc

ERLANG is very different from the procedural programming langugages. Let us see the major differences

2.1 Variables can be assigned only once
It may seem to be a misnomer - the variables can be assigned a value only once!

2.2 No iteration, only recursion
ERLANG doesnt support iteration, you have to implement your logic in a recursive manner. I am not sure, why the langugage designers chose this strategy, it may have some relations with the previous limitation - a variable can be assigned only once, and hence we cannot have a loop counter

But there are other languages which dont support iteration, like, PROLOG, LISP etc

2.3 There are no pointers
Pointers are not there - but you dont need a pointer in a ERLANG world.

2.4 Functions look like clauses in predicate logic
Clauses evaluates to values, and there is nothing like a RETURN from a function.
PROLOG is exactly like this. There are no functions in PROLOG, only clauses.

1 comment:

Unknown said...

The author makes the remark:

"But there are other languages which dont support iteration, like, PROLOG, LISP etc"

In fact, LISP supports iteration quite happily, should you choose to use it. See the "dotimes" and "do" special forms.