Functional Programming, Exam
Functional Programming, Exam
Definition
Functional programming is a programming paradigm that treats computation as the
evaluation of mathematical functions and avoids changing state or mutable data. It
emphasizes declarative programming (what to do) over imperative programming (how to do
it). This paradigm is based on the concept of pure functions, first-class functions, and
higher-order functions.
Key Features
1. Pure Functions: Functions always produce the same output for the same input and do
not cause side effects (like modifying global variables).
2. First-Class Functions: Functions are treated as first-class citizens; they can be
assigned to variables, passed as arguments, and returned from other functions.
3. Higher-Order Functions: Functions that can take other functions as arguments or
return them.
4. Immutability: Data does not change after it is created. New data structures are
created instead of modifying the existing ones.
5. Recursion: Functional programming relies heavily on recursion instead of loops.
6. No Side Effects: Functions don't alter the state outside their scope.
Example in LISP
Problem: Compute the factorial of a number.
Explanation:
1. Pure Function: The factorial function depends only on its input n. It has no side
effects and does not modify any external state.
2. Recursion: Instead of a loop, recursion is used to calculate the factorial.
3. Immutability: No mutable variables are used; the computation is performed purely
through function calls.
Example Usage:
Explanation:
1. First-Class Functions: The function square is passed as an argument to mapcar.
2. Higher-Order Function: mapcar is a higher-order function that applies square to
each element of the list (1 2 3 4 5).
Conclusion
LISP exemplifies the functional programming paradigm with its emphasis on recursion,
immutability, and first-class functions. Understanding these concepts in LISP helps
programmers embrace functional thinking, even in other programming languages.
State Management Avoids mutable state, uses immutability Relies on mutable state
………………………………………………….
7. Benefits of Functional Programming
1. Modular Code:
Each function performs a single task, making code easier to test and maintain.
2. Parallel Execution:
Lack of shared mutable state makes functional code ideal for parallel computing.
3. Easier Debugging:
Pure functions are deterministic and do not depend on external state.
4. Mathematical Rigor:
Functional programming aligns closely with mathematical reasoning, making it easier
to prove program correctness.