Computer Science – 20.1 Programming Paradigms | e-Consult
20.1 Programming Paradigms (1 questions)
Login to see all questions.
Click on a question to view the answer
Functional programming is a paradigm that emphasizes evaluating mathematical functions and avoiding state changes and mutable data. Its key principles include:
- Pure Functions: A pure function always produces the same output for the same input and has no side effects (it doesn't modify any external state).
- Immutability: Data is immutable, meaning it cannot be changed after it's created. Instead of modifying data, new data is created based on existing data.
- First-Class Functions: Functions can be treated like any other data type – they can be passed as arguments to other functions, returned as values from functions, and assigned to variables.
- Recursion: Recursion is often used as a control flow mechanism instead of loops.
Differences from Imperative and OOP:
- State Management: Imperative programming relies heavily on mutable state, which can make programs harder to reason about and debug. OOP also deals with mutable state within objects. Functional programming avoids mutable state entirely. Instead of modifying state, functional programs create new state by applying functions to existing data.
- Side Effects: Imperative and OOP programs often have side effects – actions that modify the program's state outside of the function's scope. Functional programming strives to eliminate side effects. Pure functions, by definition, have no side effects. This makes functional code easier to test and reason about.
- Data and Control Flow: Imperative programming uses state changes and control flow statements to manipulate data. OOP uses objects and method calls. Functional programming uses function composition and recursion to manipulate data, avoiding state changes altogether.
Functional programming promotes code that is more predictable, testable, and easier to parallelize because it avoids the complexities associated with mutable state and side effects.