Functional Programming
Class Notes: Functional Programming (FP)
---
# Functional Programming (FP)
## What is FP?
- A programming paradigm where computation is treated as the evaluation of mathematical
functions.
- Avoids changing state and mutable data.
## Core Concepts
- **Pure functions:** Same inputs always give same outputs. No side effects.
- **Immutability:** Data isn't changed; instead, new data structures are returned.
- **Higher-order functions:** Functions that take functions as arguments or return functions.
- **Recursion:** Often used instead of loops.
## Example
def square(x):
return x * x
nums = [1, 2, 3, 4]
squares = list(map(square, nums))
print(squares) # [1, 4, 9, 16]
- `map` is a higher-order function. `square` is pure.
## Benefits
- Easier to test and debug.
- Concurrency is safer because no shared mutable state.
- Code can be more concise and expressive.
## Common Pitfalls
- Can be hard to read for newcomers (many small functions).
- Recursion can lead to stack overflows if not managed well.
## Typical Use Cases
- Data transformations.
- Parallel processing (pure functions are easier to distribute).
- Declarative code (describes what, not how).