Exploring the Real Power of Functional Programming


We have been programming with object-oriented technology for quite a while. But now we are moving away from it.

Functional Programming is getting lot of attention nowadays. Even every mainstream language is now supporting functional style i.e Java, C++, C# etc. Basically, it is one of the paradigm of writing code where we write less code and do more.

Why do we really care about it ?

Around 2003, when people realized that single-core processor is not enough so they started developing multi-core processors.Writing multi-threaded application was really hard. On a single processor, multi-threaded application is more like a multi-tasking.  But in a multi-threaded multi-core system, things are quite different. An application that may be broken already, may pretend to work correctly on a single-core but on a multi-core processor it ends up being broken. One of the reason is that on multi-core system, threads are on steroids they are running continuously so they can access more of the data much more rapidly. As a result, it has become problematic to write programs correctly and can make it run concurrently.  So it has become huge problem for us as we develop applications.  Another problem arises from having mutable states. It is extremely difficult to work with mutability especially when multiple threads start sharing it.

And the more mutability means more error-prone the code . Whereas functional programming is inherently thread safe.

What is problem with mutable state ?

  1. Hard to reason
  2. Hard to make concurrent
  3. Hard to parallelize

Functional programming prefers declarative style of coding over imperative style. Declarative style is less verbose, focus on assignment less programming and using pure functions.

What is pure function ?

A pure functions gives exactly the same result no matter how many times you ask as long as your input and output are exactly the same.

For example, We will see the same code in both style of coding:

def factorial(n: Int): Int = {
var result = 1
var i = 1
while (i <= n) {
result = result * i
i = i + 1
}
result
}

def factorial(num:Int): Int = {
if(num == 1) num
else
num * factorial(num - 1)
}

If we look above two approaches of solving same factorial problem.  First approach is using imperative style of coding, where there are lots of mutation, too verbose and we have to tell what and how to do at every step .

But second approach is declarative style of coding which is assignment-less, concise, more expressive, thread-safe, explicit mutation less and we are not telling how to do at every step.

When we talk or heard about functional programming people usually think that immutability and higher order functions are extremely important.  But the real charming feature of functional programming are:

  1. Functional Composition
  2. Lazy Evaluation

Functional Composition makes the code more expressive, concise, easier to understand.

For example, find all even numbers, greater than 5 and double their value.

scala> val list = (1 to 10).toList
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> list.filter(_ > 5).filter(_ % 2 == 0).map(_ *2)
res20: List[Int] = List(12, 16, 20)

Code is very expressive, easy to understand that what is happening at every step, highly cohesive and there is no explicit mutation.

But one thing to notice, it creates lots of intermediate collections while computing final result. To avoid unnecessary computations lazy evaluations adds efficiency to your code.

Laziness leads to efficiency in code. Now we are not making copies and copies of object. You can defer execution until a much later time and have those executed very nicely that’s one of the biggest benefit you get out of this.

For example,

scala> list.view.filter(_ > 5).filter(_ % 2 == 0).map(_ *2).toList
res22: List[Int] = List(12, 16, 20)

Now, it will be evaluating lazily. It will never create intermediate collections. It will start evaluating it when we actually need the result. In our case, when we do .toList , it starts executing it. So, it never waste performance. It is very hard for it to be efficient without laziness.

So, the biggest benefit of functional programming is you get code clarity. You don’t need to waste time to figure out what is happening at every step. There is no mutation and can easily make concurrent. When functional compositions meets with lazy evaluation from that point reactive programming starts.

The main aim of this blog is to understand the essence of functional programming. I have used Scala for examples. In our next blog, we will go more deeper to understand the lazy evaluation.

Please feel free to suggest or comment!

References:

1) Thinking and Programming in Functional Style 

2) Functional Style

 

 

About Mahesh Chand Kandpal

Explorer + Technology Enthusiast + Foodie + Movie Buff
This entry was posted in Functional Programming, Java, Scala and tagged , , , , . Bookmark the permalink.

3 Responses to Exploring the Real Power of Functional Programming

  1. Functional programming reminds me of why I like SQL – lazy evaluation sounds similar to how a good cost-based SQL optimizer finds the most efficient way to execute the individual atomic-level operations in order to produce the desired result that we have ‘declared’ in SQL. Am I thinking about this correctly?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s