Explore the foundational concepts of functional programming, including pure functions, immutability, higher-order functions, and key paradigms. This quiz is designed to help learners solidify their understanding of functional programming essentials for improved code quality and maintainability.
Which statement best describes a pure function in functional programming?
Explanation: A pure function consistently returns the same result for equal arguments and does not affect or rely on any external state—meaning it has no side effects. Functions that modify global variables have side effects, making them impure. Functions producing random results for the same input are inherently impure. The necessity of calling a function only once is unrelated to purity; pure functions can be called any number of times.
Why is immutability important in functional programming when working with data structures?
Explanation: Immutability ensures that once data structures are created, they cannot be changed, making code easier to reason about and reducing unexpected side effects. Allowing unrestricted changes to variables would increase potential errors and is contrary to functional programming principles. Depending on external state reduces predictability, while requiring all functions to be recursive is not a consequence of immutability.
Given the following description, what is a higher-order function? A function that takes other functions as arguments or returns a function as its result.
Explanation: Higher-order functions either accept functions as parameters, return functions as output, or both. Having multiple parameters does not make a function higher-order unless those parameters are functions. Returning only integers describes return type, not order. Limiting use to lists is incorrect, as higher-order functions can operate on various data types.
What does it mean for an expression to have referential transparency in functional programming?
Explanation: Referential transparency means expressions can be substituted for their values without affecting the program, which supports predictability and maintainability. Throwing exceptions for invalid input is not related. Relying on timing or modifying external variables contradicts the principle of referential transparency.
How does function composition typically work in functional programming, given two functions f and g?
Explanation: Function composition means combining functions so that the output of g is fed as input to f, resulting in a new function. Modifying either function or requiring side effects contradicts core functional programming ideas. Functions do not need matching input types except where input/output types align, and recursion is not required for composition.