Functional programming is not just an academic concept. Pure functions, immutability, and composition lead to cleaner code.
Key Principles¶
- Pure functions: Same input → same output, no side effects
- Immutability: Data is not mutated, new data is created
- First-class functions: Functions as values
- Composition: Composing small functions
Practical Examples¶
Functional Programming Principles¶
from functools import reduce numbers = [1, 2, 3, 4, 5] doubled = list(map(lambda x: x * 2, numbers)) evens = list(filter(lambda x: x % 2 == 0, numbers)) total = reduce(lambda a, b: a + b, numbers)
List comprehension (pythonic)¶
doubled = [x * 2 for x in numbers] evens = [x for x in numbers if x % 2 == 0]
Composition¶
from functools import reduce def compose(*fns): return reduce(lambda f, g: lambda x: f(g(x)), fns) process = compose(format_output, validate, parse_input) result = process(raw_data)
JavaScript FP¶
const users = [{ name: ‘Jan’, age: 30 }, { name: ‘Eva’, age: 25 }]; const names = users.map(u => u.name); const adults = users.filter(u => u.age >= 18); const totalAge = users.reduce((sum, u) => sum + u.age, 0); // Immutability const updated = { …user, age: 31 }; // Spread, not mutation const newList = […items, newItem];
Key Takeaway¶
Pure functions for testability, immutability for predictability, map/filter/reduce instead of for loops.