K
K
Kuusandr2019-05-21 23:28:12
Programming
Kuusandr, 2019-05-21 23:28:12

What is the difference between procedural and functional programming?

As a typical "dinosaur", I thought about the question of what is the difference between the two programming styles. From my dinosaur point of view, it's the same thing.
Or are there any such differences?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Anton Spirin, 2019-05-22
@rockon404

Example in JavaScript context:
Procedural style:

const array = ['first', 'second'];

let output;

function allOdd(words) {
  let result = true;

  for (let i = 0; i < words.length; ++i) {
    const len = words[i].length;

    if (len % 2 !== 0) {
      result = false;
      break;
    }
  }

  return result;
}

output = allOdd(array);

alert(output);

Functional Style:
function length(string) {
  return prop('length', string);
}

function odd(number) {
  return equals(modulus(number, 2), 0); 
}

function allOdd(...words) {
  return every(compose(odd, length), words);
}

alert(allOdd('first', 'second'));

The implementations of prop , modulus , equals , every and compose are left out. I think it's easy to understand from their name what result they return.

E
Evgeny Romashkan, 2019-05-22
@EvgeniiR

FP does not imply mutable state.
Procedures change some general state.

V
Vitaly, 2019-05-30
@daruvayc0

In declarative programming, you make it clear: I want the factorial of n to be n times the factorial of n-1 (as in the definition of factorial in mathematics). 061936c90772779b902414ec897902cc4b61ca06Declarative is what.

const factorial = (n) => {
  return (n === 0) ? 1 : n * factorial(n-1);
}

In imperative , you order to move clearly in steps - multiply this by this while the countdown is on and some numbers are remembered.
const factorial = (n) => {
  const iter = (counter, acc) => {
    return (counter === 0) ? acc : iter(counter - 1, counter * acc);
  }
  return iter (n, 1);
}

Imperative is like.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question