Purity

In functional programming, a function is referred to as a pure function if all its input arguments are known and all its output results are also well known and declared; or we can say the input and output result has no side-effects. Now, you must be curious to know what the side-effect could be, let's discuss it.

Let's look at the following example:

Public int sum(int x)
{
return x+x;
}

In the previous example, the function sum takes an integer input and returns an integer value and predefined result. This kind of function is referred to as a pure function. Let's investigate the following example:

Public void verifyData()
{
Employee emp = OrgQueue.getEmp();
If(emp != null)
{
ProcessForm(emp);
}
}

In the preceding example, the verifyData() function does not take any input parameter and does not return anything, but this function is internally calling the getEmp() function so verifyData() depends on the getEmp() function. If the output of getEmp() is not null, it calls another function, called ProcessForm() and we pass the getEmp() function output as input for ProcessForm(emp). In this example, both the functions, getEmp() and ProcessForm(), are unknown at the verifyData() function level call, also emp is a hidden value. This kind of program, which has hidden input and output, is treated as a side-effect of the program. We cannot understand what it does in such functions. This is different from encapsulation; encapsulation hides the complexity but in such function, the functionality is not clear and input and output are unreliable. These kinds of function are referred to as impure functions.

Let's look at the main concepts of pure functions:

  • Immutable data: Functional programming works on immutable data, it removes the side-effect of variable state change and gives guarantee of an expected result.
  • Referential transparency: Large modules can be replaced by small code blocks and reuse any existing modules. For example, if a = b*c and d = b*c*e then the value of d can be written as d = a*e.
  • Lazy evaluation: Referential transparency and immutable data give us the flexibility to calculate the function at any given point of time and we will get the same result, because a variable will not change its state at any time.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset