Functional Programming

What it is? what its all about?

Here is one of the concepts I’ve found:

In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions or declarations instead of statements. In functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) each time. Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming. [1]

In functional programming we create functions that given any parameter the result of executing that function many times with that given parameter the returning value is always the same, for example:

var addTwo = function(x) { 
  return x + 2; 
}

x = 4;
y = addTwo(x);
console.log(x);
> 4
Console.log(y);
> 6
addTwo(x);
> 6
console.log(x);
> 4

It doesn’t matter how many times you execute the addTwo function with the same parameter the result will always be the same. The data was not mutated (x = 4) and only the result of applying the function is the one  that has a different value(y = 6). You can run this code in Fiddle or in the console of your browser and see it by your self.

This is a very basic example but it illustrates the concept and it is the easiest way I found to explain it. Further in the blog I am hoping to add more complete and complex examples of it.

The other important part of the concept is that programming is done with expressions/declarations and no statements, the key difference between them is that expressions evaluates into something ( f(x) = x + 2) and statements are actions to be carried out by the computer  (console.log(‘This is a statement’)).

If you have any observations or questions just let me know.

Sources:

  1. Wikipedia: Functional Programming

 

Facebook Comments