What is Pure Function | Functional Programming in Scala

Reading Time: 2 minutes
Functional Programming

What is Functional Programming?

Firstly, Functional programming is a programming paradigm in which everything is bound using pure mathematical functions. It’s a declarative programming approach. In contrast to an imperative style, which focuses on “how to solve,” it focuses on “what to solve.” Instead of statements, it uses expressions. A statement is executed to assign variables, but an expression is evaluated to create a value. In addition, Those functions have some unique characteristics.

Components of functional programming

  • Pure functions
  • Recursion
  • Referential transparency
  • Functions are First-Class and can be Higher-Order
  • Immutability

What is a Pure Function?

Pure functions are normal functions with some characteristics :

  1. Total / Not Partial
  2. No Randomness
  3. No Side Effects
  4. Not Null
  5. No Exception
  6. No Mutation

Example of Pure Function

def add(a: Int, b: Int): Int = a + b

Example of Not a Pure Function

def divide(a: Int, b: Int): Int = a / b

The ‘divide’ function passes all the parameters of being a pure function but if in case ‘a’ will be divided by 0, Then it will throw an exception which will make it not a pure function.

Not pure function

Advantages and disadvantages of Functional Programming

Advantages:

  1. This programming aids in the effective resolution of difficulties.
  2. It improves modularity.
  3. It allows us to implement lambda calculus in order to solve complex problems
  4. Some programming languages support nested functions so it improves the maintainability of the code
  5. It reduces complex problems into simple pieces so that it will be easy to solve.

Disadvantages:

  1. It’s difficult to grasp for novices, hence it’s not a beginner-friendly paradigm approach for new programmers.
  2. Maintenance is difficult during the coding phase when the project size is large
  3. Moreover, Reusability in Functional programming is a tricky task for developers

For further information on functional programming wait for the next blog…

Reference

For more details please visit: https://en.wikipedia.org/wiki/Functional_programming

Written by 

Pallav is working as Software Consultant at Knoldus Inc. He is a technology enthusiast and a keen learner with more than 2 years of experience. He works as a Quality Catalyst in the organization. He has a good understanding of programming languages like Java and Scala. He likes to listen to songs and playing table tennis.

Discover more from Knoldus Blogs

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

Continue reading