Can anyone please provide me with an example that can help me to understand Procedural, functional, Logic and Object Oriented programming models side by side by using nearly same example-problem.
Please give me example code-snippets of the somewhat same problem using Procedural, Functional, Logic and OO programming languages.
Let's try simpler example - just calculating n-th Fibonacci number.
First, procedural (in Pascal):
program Fibonacci;
function fib(n: Integer): Integer;
var a: Integer = 1;
b: Integer = 1;
f: Integer;
i: Integer;
begin
if (n = 1) or (n = 2) then
fib := 1
else
begin
for i := 3 to n do
begin
f := a + b;
b := a;
a := f;
end;
fib := f;
end;
end;
begin
WriteLn(fib(6));
end.
This example shows features of procedural languages:
Second, object oriented (in Python):
class Fibonacci:
def __init__(self):
self.cache = {}
def fib(self, n):
if self.cache.has_key(n):
return self.cache[n]
if n == 1 or n == 2:
return 1
else:
a = 1
b = 1
for i in range(2, n):
f = a + b;
b = a;
a = f;
self.cache[n] = f;
return f;
fibonaccyCounter = Fibonacci()
print fibonaccyCounter.fib(6)
Actually the problem is not worth creating a class, so I added caching of already calculated results.
This example shows:
Not shown but we can e.g. descend this class from abstract class returning n-th member of some sequence. By subslassing we get class defining Fibonacci sequence, sequence 1,2,3..., sequence 1,4,9,16,... etc.
Third, in functional style (Haskell):
import Text.Printf
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
main = printf "%d\n" (fib 6)
Following features of a functional programming paradigm are demonstrated:
But the main feature of functional languages is that functions are first class objects.
This can be demonstrated by other implementation of fib
:
fib n = fibs!!n
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
Here we are passing fibs
function as parameter to zipWith
function.
This example also demonstrates lazy evaluation: "infinite" list is computed only to extent it is needed for other functions.
By the way, functional does not necessary mean not object oriented. An example of programming language that is both functional and object oriented is Scala.
Prolog:
fib(1, 1).
fib(2, 1).
fib(X, Y):-
X > 1,
X1 is X - 1,
X2 is X - 2,
fib(X1, Z),
fib(X2, W),
Y is W + Z.
main :-
fib(6,X), write(X), nl.
Following features of logic programming style can be seen:
This program could also be used to find out that Fibonacci number 8 is at 6th position in the sequence:
?- between(0,inf,X), fib(X,8).
X = 6 .