Friday, September 21, 2007

Implementing Algorithms (Part 1)

I just started learning this language which belongs to a class of languages known as Functional Language.

For starters, I am going to demonstrate some simple stuff.

1/ Calculate Factorial


%
% Algorithm to calculate the Nth Factorial
%
-module(fac).
-export([factorial/1]).

factorial(0) -> 1;
factorial(1) -> 1;
factorial(N) when N > 0 -> N * factorial(N-1).

2/ Calculate N-th Fibonacci Sequence


%
% Algorithm to calculate the sum of Nth Fibonacci Sequence
%
-module(fib).
-export([fibonacci/1]).

fibonacci(0) -> 0;
fibonacci(1) -> 1;
fibonacci(N) when N > 1 -> fibonacci(N-1) + fibonacci(N-2).

In order to run the above scripts, do the following

a) Create a file call fac.erl or fib.erl (Note: name of file must be the same as the string given in the "-module")
b) Copy and paste the respective code into the respective file
c) Start up the Erlang Shell and type the following (Note the period character '.'):
c.1) c(fib).
c.2) c(fac).
If your compilation was successful, you should have the following screen

2 comments:

Anonymous said...

I hope you realize that this implementation of the Fibonacci numbers is horrendously inefficient -- O(2^n) in fact.

Raymond Tay said...

Hi Russell,

Thanks for the comments. Yes i do know its VERY inefficient but the point at that time was about demonstrating Erlang and my typical usage of it.

Cheers