What is different in  pure and impure function in scala

4/7/2023

#pure and impure function #scala #diference #pure function #impure function

# What is different in pure and impure function in scala ?

## Definition of pure function  :

In computer science and functional programming, the term "pure function" describes a function that has specific properties,
is intended to always generate the same output given the same input, and has no other dependency  side effects.

A pure function is a function that depends only on its declared inputs and its internal algorithm to produce its output .

`def double(i: Int): Int = i * 2`

"A pure function is a function that depends only on its declared inputs and its internal algorithm to produce its output. It does not read any other values from “the outside world” — the world outside of the function’s scope — and it does not modify any values in the outside world."

## Definition of Impure function  :

A impure function is a function that depends  on referrential variable or data and also  its declared inputs .it is produce its output .

"Write the core of your application using pure functions, and then write an impure “wrapper” around that core to interact with the outside world. If you like food analogies, this is like putting a layer of impure icing on top of a pure cake".

`def sum(list: List[Int]): Int = list match {`

`case Nil => 0 case head :: tail => head + sum(tail)`

`}`

Impure functions can add complexity to the code, making it more challenging to test, maintain, and reason about. Due to their possible side effects, they might also cause problems with concurrency and parallelism.

A function that does not adhere to the definition of a pure function is referred to as an impure function in computer science and functional programming. Impure functions, as contrast to pure functions, exhibit one or more of the following traits:

The drawbacks of impure functions include:

1. Complexity: When working with side effects and external state, impure functions can add complexity and make the code more difficult to comprehend, test, and maintain.

2. Potential Bugs: Due to their side effects, impure functions may result in problems with concurrency, parallelism, and unanticipated interactions.

3. Reduced Predictability: Understanding and debugging the behaviour of impure functions can be difficult due to their non-deterministic nature.

## Conclusion :

The fact that pure and impure functions are combined in real-world applications is a second important issue.

It is frequently advised to create the application's core in pure functions before employing impure functions to interact with the outside world.

Therefore ,

impure functions may be necessary in certain scenarios, particularly when dealing with I/O operations or stateful applications,

but they should be used with care and well-documented to understand their effects on the overall program.