Tuesday, April 26, 2016

Functional Programming and Procedural Programming

Procedural Programming
Derived from structured programming, based on the concept of modular programming or the procedure call Derived from structured programming, based on the concept of modular programming or the procedure call

Procedural programming uses a list of instructions to tell the computer what to do step by step. Procedural programming relies on procedures, also known as routines. A procedure contains a series of computational steps to be carried out. Procedural programming is also referred to as imperative or structured programming.

Procedural programming is intuitive in the sense that it is very similar to how you would expect a program to work. If you want a computer to do something, you should provide step-by-step instructions on how to do it. Many of the early programming languages are all procedural. Examples of procedural languages include Fortran, COBOL and C, which have been around since the 1960s and 70s.

A common technique in procedural programming is to repeat a series of steps using iteration. This means you write a series of steps and then tell the program to repeat these steps a certain number of times. This makes it possible to automate repetitive tasks.

·        The output of a routine does not always have a direct correlation with the input.
·        Everything is done in a specific order.
·        Execution of a sub-routine may have side effects.
·        Tends to emphasize implementing solutions in a linear fashion.

For Example: (Perl)

     sub factorial ( int $n ){
       my $result = 1;
       loop ( ; $n > 0; $n-- ){
            $result *= $n;
       return $result;

Functional Programming
Treats computation as the evaluation of mathematical functions avoiding state and mutable data.

Functional programming is an approach to problem solving that treats every computation as a mathematical function. The outputs of a function rely only on the values that are provided as input to the function and don't depend on a particular series of steps that precede the function.

Functional programming relies heavily on recursion. A recursive function can repeat itself until a particular condition is reached. This is similar to the use of iteration in procedural programming, but now applied to a single function as opposed to a series of steps. Examples of functional programming languages include Erlang, Haskell, Lisp and Scala.

·        Often recursive.
·        Always returns the same output for a given input.
·        Order of evaluation is usually undefined.
·        Must be stateless. i.e. No operation can have side effects.
·        Good fit for parallel execution
·        Tends to emphasize a divide and conquer approach.
·        May have the feature of Lazy Evaluation.

For Example: (Perl)
    sub factorial ( int $n ){
       return 1 unless $n > 0;
       return $n * factorial( $n-1 );