Functional Techniques
Introduction to Functional Programming
Functional programming is a paradigm that treats computation as the evaluation of mathematical functions, avoiding changing state and mutable data.
Key Functional Techniques
Lambda Functions
## Simple lambda function
multiply = lambda x, y: x * y
result = multiply(4, 5) ## 20
## Sorting with lambda
names = ['Alice', 'Bob', 'Charlie']
sorted_names = sorted(names, key=lambda name: len(name))
Map Function
## Transforming lists
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
Filter Function
## Filtering elements
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
Functional Programming Techniques
Technique |
Description |
Python Implementation |
Map |
Transform elements |
map() function |
Filter |
Select elements |
filter() function |
Reduce |
Aggregate values |
functools.reduce() |
Reduce Function
from functools import reduce
## Calculating sum using reduce
total = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
Functional Flow Visualization
graph TD
A[Input Data] --> B[Map Transformation]
B --> C[Filter Selection]
C --> D[Reduce Aggregation]
D --> E[Final Result]
Decorators
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def add(x, y):
return x + y
Partial Functions
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
Advanced Functional Patterns
- Immutable Data Structures
- Pure Functions
- Function Composition
- Recursion
- Lambda functions can be less readable
- Functional techniques may have slight performance overhead
- Use when clarity and expressiveness matter
LabEx Functional Programming Tips
- Leverage built-in functional tools
- Keep functions small and focused
- Prefer immutability
- Use type hints for clarity
By mastering these functional techniques, developers can write more concise and expressive code in their LabEx Python projects.