Skip to main content
Practice Problems

What is a pure Function?

Understanding Pure Functions

Definition of a Pure Function

A pure function is a function that adheres to two key principles:

  1. Deterministic Output: For a given input, a pure function always produces the same output. This means that the output is solely dependent on the input parameters and does not rely on any external state or data.

  2. No Side Effects: A pure function does not cause any observable changes outside its scope. This means it does not modify any external variables, data structures, or perform any I/O operations (like writing to a file or printing to the console).

Characteristics of Pure Functions

Pure functions have several important characteristics:

  • Referential Transparency: This means that a pure function can be replaced with its output value without changing the program's behavior. This property is crucial for reasoning about code and optimizing performance.

  • Easier Testing: Since pure functions do not depend on external state, they are easier to test. You can test them in isolation by providing inputs and verifying the outputs.

  • Concurrency: Pure functions can be executed in parallel without concerns about shared state, making them suitable for concurrent programming.

Examples of Pure Functions

Here are examples to illustrate pure functions:

python
def add(a, b): return a + b

In this example, the add function is pure because it always returns the same result for the same inputs and does not modify any external state.

python
def multiply(a, b): return a * b

Similarly, the multiply function is also pure for the same reasons.

Conclusion

Pure functions are fundamental in functional programming and contribute to writing clean, maintainable, and testable code. Understanding and utilizing pure functions can significantly enhance the quality of your software development practices.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems