12
Functional Programming — A new paradigm
Functional Programming
Paradigms
Scala

By now you must have heard about functional programming. I mean how could one miss it as it’s a buzz word now-a-days. There are many emerging languages popping out in the world which are known as Functional Programming or FP for short. Like Scala and Clojure and many more.

So now what’s this all about? What is the concept of FP? Why do it become buzz word in upcoming time? What are the advantages of it? And why should one prefer this over old languages?

Now there is always one WHY behind any revolution. Let’s find out answer of ours.

So as per Wikipedia,

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.

Ohh man, what is all this functions, changing state, mutable data??? I know, even I didn't understand it for the first time. Let’s try in some other way, more simple way.

Functional programming is a language consist of only PURE functions with no side-effects and nothing but just only functions, those are pure.

Isn't it more simple than above one? And yes, I emphasized more on the pure word for function. Now seriously, what is it?

As per definition of pure function,

A function with input type A and output type B is a computation which relates every value a of type A to exactly one value b of type B such that b is determined solely by the value of a.

Didn’t get it? No worries, let’s put it in this way : Pure functions are those which takes argument list as a input and whose output is some return value. Now you must be thinking that all functions are pure. After all, any function takes in values and returns a value but no, it’s not like that. For example, if function rely on the global variable or class member’s data, then it is not pure. And in such cases, return value of that function is not entirely depended on the list of arguments received as a input and can also have side effects.

So again, there is another WHY. Why use only pure function? And answer itself is in definition of impure function and it’s properties. And it’s because, pure function has a referential transparency, means it will return the same value every time for a given set of input, despite of depending on other things like system time, database state, from where it is called, etc.

Now let’s come back to FP. Still not clear? No worries, let me put it in simple words for you.

Functional programming seeks to describe what you want to do instead of specifying how you want to do.

Let’s get clear on this : Suppose you have a list of employees and you just want to fetch the name of all those employee whose salary is greater than x amount. How you will do this in Java?

private List<String> filterEmployee(List<Employee> employees) {
    List<String> names = new ArrayList<String>();
    for(Employee emp: employees){
        if(emp.getSalary() > x){
            names.add(emp.getName());
        }
    }
    return names;
}

And now see, how this can be achieved in FP. Here I'm using RxJs for sample example.

employees.filter(function(emp){
    return emp.getSal() > x;
}).map(function(emp){
    return emp.name;
});

Woohhaa, that’s it?? Is it that quite simple? Hmm..well yes, just tell what you want as a result and language will then takes care of everything else. Yeah it is, I know.

Now let’s move to FP again. In any application we would require to deal with collection and perform some small or big operations on it. And in FP, basically there are 5 main functions with which we can perform most of the operations on collection. Those are :

  1. map
  2. filter
  3. concatAll
  4. reduce
  5. zip

Let me explain one by one with respect to Java code(As being Java developer, I couldn’t choose any other languages!!) so that it'll be easy to understand how it works.

So first one is map. As per its definition,

map is the name of a higher-order function that applies a given function to each element of a list, returning a list of results.

For example consider following scenario : Suppose we have a list of employee(with name, age, dept and projects). Now write a code to retrieve only name of employees.

private List<String> getEmployeeNames(List<Employee> employees) {
    List<String> names = new ArrayList<String>();
    for(Employee emp: employees){
        names.add(emp.getName());
    }
    return names;
}

While in functional language (RxJS), it looks like below :

employees.map(function(emp){
    return emp.name;
});

2) filter : As per filter’s definition,

filter is a higher-order function that processes a data structure (typically a list) in some order to produce a new data structure containing exactly those elements of the original data structure for which a given predicate returns the boolean value true.

In simple meaning, filter works like normal water purifier. I know you are laughing but its a truth :D. Filter is used to filter out unwanted data from the list and return rest of it. Now for above example, how we will write a snippet to return all employee object whose age is greater than 40.

private List<Employee> filterEmployee(List<Employee> employees) {
    List<Employee> names = new ArrayList<Employee>();
    for(Employee emp: employees){
        if(emp.getAge() > 40){
            names.add(emp);
        }
    }
    return names;
}

And in RxJS,

employees.filter(function(emp){
    return emp.age > 40;
});

3) concatAll : It is like merging all values together and return a flat structure instead of hierarchical one. It will iterate over all sub-array in array and merge them together and return values in new, simple flat array.

Not that means “[ [1,2,3], [4,5,6], [7,8,9] ].concatAll()” will return something like this “[1,2,3,4,5,6,7,8,9]”

For above example, let’s retrieve list of project names and compare the code in Java and RxJS.

private List<String> getProjectNames(List<Employee> employees) {
    List<String> names = new ArrayList<String>();
    for(Employee emp: employees){
        for(Project prj : emp.getProjects()){
            names.add(prj.getName());
        }
    }
    return names;
}

And in RxJS,

employees.map(function(emp){
    return emp.projects.map(function(prj){
        return prj.name;
    });
}).concatAll();

I will leave you with other two for self learning. Till then you can have some experience on FP through interactive learning course. This is quite useful for beginners so go there and have some fun. Cheers !!!

Author

Notifications

?