Explore the differences between pure and impure functions with this focused quiz, designed to strengthen your understanding of functional programming concepts and their practical implications. Perfect for those seeking clear explanations and real-world scenarios on function purity and side effects.
Which of the following functions can be classified as pure if it always returns the same result for given inputs and does not modify any external state?
Explanation: A function that multiplies two numbers and returns the product is pure because its output depends solely on the input values and it does not produce side effects. Writing to a file, generating random numbers, or modifying a global variable all involve side effects or depend on factors outside the function’s input parameters, making them impure. Only the first option consistently satisfies purity requirements in functional programming.
Why is a function that updates a database record based on input considered impure?
Explanation: Updating a database record alters data outside the function’s immediate environment, which is the definition of a side effect and makes the function impure. The speed of return or dependence on the time reference is not directly relevant to purity in this context. While predictable results are characteristic of pure functions, the key issue here is the modification of external state.
If a function's output varies each time it is called with the same inputs due to the use of system time, how is it classified?
Explanation: A function that produces different outputs for the same input, such as one using the system time, is impure because its result is affected by factors other than its input parameters. A pure function cannot behave this way, so option one is incorrect. Static and procedural are unrelated programming terms in this context and do not refer to function purity.
Which statement correctly explains why pure functions are considered referentially transparent?
Explanation: Referential transparency means that a function can be replaced with its output value without changing the program’s behavior; this only occurs when output relies solely on input, as with pure functions. Altering external values, using randomness, or relying on user input breaks referential transparency, making those options incorrect.
Which scenario best describes an impure function in common programming tasks?
Explanation: Logging a message to the system console is a side effect because it changes something outside the function’s local environment, making the function impure. Summing numbers, sorting a list (if it’s not changing outside data), or returning a string’s length does not modify external state, so those options describe pure functions. Only the third option violates purity rules.