Need help from an expert?
The world’s top online tutoring provider trusted by students, parents, and schools globally.
Pure functions in functional programming are those that always produce the same output for the same input and have no side effects.
In more detail, a pure function is a fundamental concept in functional programming, a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. The idea of a pure function comes from mathematics, where a function always gives the same result if the input values are the same, regardless of how many times it is called.
A pure function has two main properties. Firstly, it always produces the same output for the same input. This is known as referential transparency. For example, if a function takes two numbers as input and returns their sum, it is a pure function because every time you input the same two numbers, you will always get the same result.
Secondly, a pure function has no side effects. This means that it does not change any state or data outside of the function. It only works with the input provided and does not alter any external variables or data structures. This property makes pure functions predictable and easy to test, as you don't have to worry about the function changing any external state.
In contrast, an impure function may produce different outputs for the same input or have side effects. For example, a function that returns the current system time is impure because it gives a different result each time it is called, even with the same input. Similarly, a function that modifies a global variable or writes data to a file has side effects and is therefore impure.
In functional programming, pure functions are preferred because they make the code easier to reason about, test, and debug. They also enable certain optimisations that are not possible with impure functions. However, it's important to note that not all functions in a functional programming language are pure; impure functions are still used when necessary, but their use is controlled and isolated to maintain the overall benefits of functional programming.
Study and Practice for Free
Trusted by 100,000+ Students Worldwide
Achieve Top Grades in your Exams with our Free Resources.
Practice Questions, Study Notes, and Past Exam Papers for all Subjects!
The world’s top online tutoring provider trusted by students, parents, and schools globally.