Hi,
In recent days, I am hearing about Functional Programming Paradigm.
Appreciate your help in advance.
Instead of explaining everything here, i suggest you read SICP (amazon.in/Structure-Interpretation-Computer-Progr…).
Once you have done that, re read the answers here.
In the land of OOP, when reading code, you have a very natural way of expressing things: Subject + Verb + Object. For example:
Peter.say('Hello World');
John.takeOut('garbage').andDumpItTo('the dumpster');
To do that, you must define a class Person and then define methods such as say(string), takeOut(what) and andDumpItTo(where) before you can instantiate objects like Peter and John. It's very easy to decompose objects in the world to smaller one, and that's the selling point of OOP.
In the functional land, you have quite a bit different way to do things: Verb + Object + Subject. This would then become:
say('Hello World', Peter);
Or in a curried versions, you have
var action = say('Hello World')
var result = action(Peter);
What is the return value of say('Hello World')? It's a function that can take another object (Peter) and then output the real result. So, what about John, given that he has to perform 2 actions. You can use a technique called function composition
var actions = takeOut('garbage') |> andDumpItTo('the dumpster');
var result = actions(John);
The |> is just an imaginary symbol indicates that results will pipe through each function, one by one: the result of takeOut('garbage', John) will be passed as the parameter of andDumpItTo('the dumpster', ...)
You will notice that, in the functional land, verbs play a very important role. You work with verbs all the time, and it's often the first thing you see in a statement. You can create a function easily and then apply the object later. A functional programmer thinks in functions such as takeOut(what, byWho) and andDumpItTo(where, whatToDump), and then he uses composition to make the whole program works.
Another concept is higher order function. Let me remind you of the Array.sort function.
var numbers = [3, 2, 7, 9, 1, 0];
var comparator = (a, b) => a - b;
var sortedNumbers = numbers.sort(comparator);
What do do pass to the sort() function? Another function. While this is unusual in OOP, people do it ALL THE TIME in FP. You can think of it like strategy pattern in OOP.
So, as you can see, in FP, people love functions. They create it in various ways and functions stand freely as first-class citizens. It does not need an object to tells it what to do. Function can be passed to another function, it can be the result of another function. A function should be pure, that is, the output is calculated based on the input.
Let's take a look at this one:
var sayPure = (name) => 'Hello ' + name;
var sayImpure = (name) => this.greeting + name;
Well, what are the results when I pass 'World' into sayPure and sayImpure? If you can answer that confidently, then you'll understand the importance of pure functions when it comes to testability and ease of reasoning. Isn't the impure version what you always do in OOP?
I would suggest ClojureScript since it's easier to pick up than Haskell, and there's a chance to use it in real world. I've been writing pages in ClojureScript for some months. There's already good answers on FP and JavaScript. I want to talk based on my view.
Programming is to control complexity. OOP told us a lot about model real world with objects and make them communicate with each other. However, there's more we can do. If you see programs in the the way of FP, you find that pure functions are great tools to control complexity and mutable states, IO, these things add to complexity. Then as we try to build larger apps, we may know more about which parts are reliable and which parts are complicated intrinsically. I think this thing helps a lot.
Functional Programming is a fundamentally different way of thinking about programs than Object Oriented Programming. In OOP you model the world in terms of classes and objects. Its like how biologists would classify things based on taxonomy. Classes define the behaviour and Objects maintain state. Now because the state of the data that an object holds can be changed by other objects (mutable data) , you need to implement data hiding in OOP. Also, in the case when some piece of data needs to be accessed by multiple objects you need to implement synchronization techniques like locks, semaphores, monitors etc, else there is a risk of data corruption.
FP in contrast is a different way of looking at the world,there are no classes and objects, and instead of having mutable data as in OOP, you treat data as immutable, something that can never change, hence data can be accessed concurrently without any risk. Instead of classes and objects, FP models the world in terms of functions. Functions access data but never ever change it, given some input, they always return the same value and also don't have any side effects anywhere else like for example changing some other piece of data outside their scope etc. Hence functions in FP are known as 'pure functions'. For example consider the function below:
function add(x,y) {
return x + y;
}
Given some value of x and y , the add function will always return the same value, also it does not change anything else anywhere in the program, hence it is an example of a 'pure function'. In contrast, consider the functions below:
count = 0;
function increment(n) {
count += n;
}
function isEven() {
return count % 2 == 0;
}
In the above example, the increment function changes the value of count which is outside of its own scope, and in the second example, the isEven function returns different values at different times, based on whether count is even or odd. Hence both are examples of impure functions.
Also, in addition to immutable data , functions in FP themselves are data and can be passed around as data. Hence functions in FP are referred to as 'first-class functions' . Also functions that accept other functions as input or return functions are known as 'higher order functions'. For example consider the function below:
function map(f, arr) {
result = f(arr);
return result;
}
I can now do this:
function add(arr) {
sum = 0;
for(i = 0 ; i < arr.length ; i++) {
sum += arr[i];
}
return sum;
}
function multiply(arr) {
product = 1;
for(i = 0 ; i < arr.length ; i++) {
product *= arr[i];
}
return product;
}
map(add,[1,8,10]); //Returns 19
map(multiply,[1,8,10]); //Returns 80
You can see how i reuse the map function to do different things on the same array that i pass to it, based on what function i pass to it as the first parameter. The map function treats the function passed to it as data and can use it. Hence map is an example of a 'higher order function'.
Now you would ask why we need to bother about such things as immutable data and whats wrong with OOP. There is nothing wrong with OOP, but FP has certain advantages over it. For example, you know that computer programs are run by the processor in a computer. Computer processors have hit the limit of 'Moores Law' and have stopped getting any more faster. To counter this situation, hardware manufacturers now manufacture processors with multiple cores so that a processor can execute multiple programs/processes in parallel, in order to get more speed benefit from a single chip.
In order to take advantage of multi-core processors , as programmers , we need to write programs in such a way that they can easily be run in parallel on all cores available to us. Now, as i mentioned before when writing parallel programs there is a risk of data getting corrupted if multiple processes can access it at the same time. And here is where the immutability offered by FP comes into play. Since data is immutable we can easily parallelize our programs, taking advantage of multi-core processors and also don't have to worry about accidental modification of data. So to answer your question if you should learn about FP then i would say, definitely yes, as the world is moving to multi-core processors and parallel programming, so it would be good tool to have in your programming tool belt.
Coming to languages that support FP, i would like to make a distinction between languages that have a mix of OOP and FP and others that are purely functional. Languages like Javascript, Ruby, Python etc provide functional programming features but are not purely functional because they don't strictly enforce data immutability. It is possible to have higher order functions in these languages but it is also possible to have mutable data, also they support OOP concepts of classes and objects.
On the contrary languages like for example Haskell, Erlang, Elixir etc are purely functional languages because they don't allow mutable data. So based on your background and preferences you can take a pick.I would say in addition to learning how you can do FP in languages like say Javascript, Python etc it would be helpful to know atleast one purely functional language, as it would definitely make you a better programmer.
If want you want to get started with Haskell there is a great freely available online reference called 'Learn You a Haskell for great good ' (http://learnyouahaskell.com) . Coming from a Ruby background i have recently been looking into Elixir, and really enjoying it. Others can probably pitch in with their own suggestions. Hope this post has given you some insight into FP and all the best in your attempts at learning it. Have fun ! :).
FP is a supreme paradigm and very simple. OOP is based on functional. Think about it like math in school where you got simple functions like f(x), y = 5 + 10x, etc.
Pure functions:
2.1. same function call with same arguments always will return same result,
2.2. no side effects - function does not depends on time, weather and does not change anything outside of it
// OOP
class Model {
...
}
class User extends Model {
getName() { return this.name }
setName(name) { this.name = name }
}
// FP
function model(table, id) {
return sql_array('SELECT * FROM ? WHERE id = ?', [table, id]);
}
function user(id) {
return model('users', id);
}
Actually very many. C, Python, Lua, C#, Haskell, Perl, Erlang, Elixir, JavaScript, PHP, ...
JavaScript is primarily a functional language, same with PHP
Yes, you should, and a lot.
Good presentation from SoundCloud why they reject the most JS applications.
Another interesting slide on Fun with Functions.
Read/watch/follow Eric Elliott, JS architect writting modern articles about JS and FP.
The Two Pillars of JavaScript — Pt 2: Functional Programming.
Master the JavaScript Interview: What is a Pure Function?
In a restricted sense ,functional programming means programming without mutable variables ,assignments ,loops and control structures .
In a wider sense, functional programming paradigm focuses on functions. When we focus on functions ,we think about what is to be done rather than how .
Example,
Suppose you have to calculate sum of the squares.
In an imperative style you would start thinking about initializing the sum variable as 0 , iterating over the list ,square each element by the number and adding the squares to the sum variable.
Here there is iteration and mutable variables.
In functional thinking you would identify functions to be used .
There are three words in this program: take,map and sum . Each of those words refers to a function. The “.” simply means: call the following function and the give it result of current function as the argument.
That’s it. The take function simply takes the first n integers starting from 1. map transforms this list by squaring each element of the list and produces another list sum takes a list and sums up to give one value.
Each function does only one job and we solve the problem in terms of functions and not in steps.
So ,functional programming is about applying function to data rather than bringing data to functions.
In a way , it's similar to using axe(function) to cut the wood(data) rather than bringing the wood to axe .
Natural ! Isn't it?