Functional programming concepts in Javascript & Java – 1 4


In this post, we will cover

  1. What is functional programming?
  2. Higher order function
  3. An example of higher order function

 

Functional programming

Lambda Calculus

The concept of functional programming is based on lambda calculus (early 1930). It took nearly 20 years for the first functional programming language to evolve; Lisp (founded in 1958; paper published by John Macarthy). Lisp is one of the forerunners to today’s modern functional programming languages. There are many languages today that are functional or supports the style. Some of them are hybrid and support multiple programming paradigms.

 

Imperative to declarative

In the beginning, computer systems were considered to be complex and were expensive. Processors and memories were sparse. These factors directed the style of programming. For instance, generation of a long finite series through a stateless recursive program could blow few vacuum tube memories. However, the modern computer will have no problem in performing such an operation as it has muti-core processors and few billion bits at its disposal. This change in technology has helped functional programming to gain traction.

A single Apple iPhone 5 has 2.7 times the processing power than the 1985 Cray-2 supercomputer.

As a programmer what you would have mostly learned and practiced is an imperative paradigm.

In the imperative style, one would

  • Use statements or expressions
  • Often mutating states

In short, you define “How to do”

In the declarative style, you will

  • Define the logic of computation
  • Without describing the flow

In short, you define “What to do” and not “How to do”.

Functional programming

The functional programming paradigm facilitates declarative style thus favoring “fewer side-effects.” As there is less or no explicit mutation, this style would help you to foster parallelization and memorization.

Functional programming is based on the following.

  • Functions as a first class citizen.
  • Pure functions

Functions as a first class citizen.

Functions that can either take other functions as arguments or return them as results forms the essence of functional programming. Just like object-oriented programming, where the objects are the first class citizen and being passed and mutated, in the functional programming paradigm, function are the first class citizen that can be passed around.

Let’s see how this can be achieved in javascript.

We are going to write a predicate function that will test for some condition involving its arguments and returns true or false.

Javascript had first class functions from inception.

function validate(number,predicate){
    if (predicate){
        return predicate(number);
    }
    return false;
};

The validate function takes in two arguments.

  • Number
  • a function()

The “validate function” above is a higher order function as it takes another function as a parameter.

Let’s call the validate function and also provide the logic for validation.

Call 1

    validate(someNumber,function(arg){
                        return arg%10 == 0;
                    }
    )

Call 2

    validate(someNumber,function(arg){
                        return  arg > 1000;
                    }
    )

Thus the caller defines the logic for validation. This enables the “function validate” to exhibit polymorphic behaviour.

The entire code

validate  = function(number,predicate){
    if (predicate){
        return predicate(number);
    }
    return false;
};

console.log("Begin: Validate example")
console.log(
    validate(10,function(number){
        return number%10 == 0;
    })
);

console.log(
    validate(100,function(number){
        return number > 1000;
    })
);

console.log("End: Validate example");

Closing notes

ES6 has introduced the arrow functions; with this, the above calls could be much simplified. For instance,

validate(10,function(number){
        return number%10 == 0;
})

will become

validate(10,number => number%10 == 0)

which improves the readability of the code. Working example of the code can be found here.

In the next post, we will discuss

  1. How to extend write Higher order functions in Java
  2. Understand pure functions
  3. Write a pure function in Java/Javascript

until then have a good Christmas 2016.

 

jw

In pursuit of writing good code; just like many of you, I regularly foray into the realms of unknown and like the little Alice I am often fascinated by the wonderland of modern practices, frameworks and languages. Reminiscing on my past, destiny has been kind to me and has taken me to unrelated technologies; Cobol, Excel, DBase, Unix, Sybase, C++, VC++, Java to name a few. It has allowed me to participate in various phases of the development cycle and made me teach technology to hundreds. Travelling miles in my journey, I am at this juncture where I have decided to share my experience and knowledge. I am hopeful that my knack for understanding the technology will help you to go an extra mile in your pursuit of writing good code. – John Wilfred

 


Leave a comment

Your email address will not be published.

4 thoughts on “Functional programming concepts in Javascript & Java – 1

  • Ruby Daniel Siju

    Good Stuff John !!! Thanks for sharing. I am newbie in FP but amazed by its features: – Replacing Iteration by Recursion introduces immutable variables and stateless programming. – Immutable variables makes parallel programming easier by eliminating the need of locking and avoiding deadlock. It also had minimal or ignorable drawback: – Requires lot of memory as FP’s don’t have state and it creates new objects instead of modifying existing objects. Thanks for triggering my curiosity in this subject. Awaiting your next blog !!!!!