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):
This example shows features of procedural languages:
Second, object oriented (in Python):
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):
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:Here we are passing
fibsfunction as parameter tozipWithfunction.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:
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: