Functional Programming is a way of writing computer programs in the same manner as mathematical functions. They are categorized into two groups
1.Pure Function
2.Impure Function

Pure Function

A function with no side effects is called Pure Function. So this begs the question “what are side effects”. A function is said to have side effects if the output depends on something else apart from input. So the output of Pure Function only depends on the input to the function . This means as long as same inputs are passed the output will remain same.

Example OF PURE FUNCTION

Lets create a function which takes an Integer and returns a value by adding 5 to it.

def funcadd(x: Int):Int={ x + 5 }

If you are having difficulty in understanding the function its ok, in future when we cover a blog on Scala function this would mean more sense. But as of now try to understand it as ‘x’ is the value which is received and the function returns X + 5 . So if we supply X=10 then the function returns X + 5 which is 15. As this is a Pure Function ,each time we supply 10 as input the return value is 15.

Impure Function

A function is said to be impure if the output depends on something else other than the input to the function. So the output of pure function may vary even if same inputs are provided multiple times.

EXAMPLE OF IMPURE FUNCTION

Lets create a function which takes an Integer and returns a value by adding a number which is present in a file.

def funcadd(x: Int):Int={ x + "value fetched from a file" }

The above is not a correct way of fetching data from file, but to make the function look simpler I have written it in this way. Now lets pass the same number 10 to x , if the file contains value 5 then the return value is 15. But, if the file contains 7 the return would have been 17. So this is an impure function as the output depends on input parameter and also on some parameter within the function.

So while using any Functional Programming language we should aim to write Pure Functions as much as possible.

In the next chapter we will learn about SCALA TYPE INFERENCE.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from UnderstandingBigData

Subscribe now to keep reading and get access to the full archive.

Continue reading