1. What is Functional Programming?
Functional Programming (FP) is a programming paradigm that treats functions as first-class citizens, meaning they can be passed as arguments, returned from other functions, and stored in variables. It emphasizes immutability, pure functions, and higher-order functions.
Core Principles of Functional Programming:
- First-Class Functions: Functions can be assigned to variables, passed as arguments, and returned.
- Higher-Order Functions: Functions that take other functions as arguments or return them.
- Pure Functions: Functions that do not modify external state and always produce the same output for the same input.
- Immutability: Avoids modifying existing data; instead, it returns new data.
- Recursion: Preferred over loops in some FP styles.
2. First-Class and Higher-Order Functions
First-Class Functions Example
def square(x):
return x * x
f = square # Assign function to a variable
print(f(5)) # Output: 25
Functions are treated like any other variable.
Higher-Order Functions Example
def apply_function(func, value):
return func(value)
print(apply_function(square, 4)) # Output: 16
apply_function()
takes a function as an argument.
3. Pure Functions
A pure function:
Depends only on input arguments
Produces the same output for the same input
Has no side effects (no modifying global variables or I/O operations)
def add(a, b):
return a + b # No modification of external state
print(add(3, 4)) # Output: 7
Pure functions improve debugging and parallel processing.
4. Immutability
Functional programming avoids modifying data in-place. Instead, it creates new copies.
original_list = [1, 2, 3]
new_list = original_list + [4] # Creates a new list instead of modifying the original
print(original_list) # Output: [1, 2, 3]
print(new_list) # Output: [1, 2, 3, 4]
Immutability prevents unexpected side effects.
5. Functional Programming with Built-in Functions
Python provides several built-in functions for functional programming:
Using map()
Applies a function to each item in an iterable.
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
Using filter()
Filters elements based on a condition.
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Output: [2, 4]
Using reduce()
Performs a cumulative computation.
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
6. List Comprehensions (Functional Alternative to Loops)
List comprehensions are concise functional constructs.
numbers = [1, 2, 3, 4]
squared = [x**2 for x in numbers] # Equivalent to map()
print(squared) # Output: [1, 4, 9, 16]
evens = [x for x in numbers if x % 2 == 0] # Equivalent to filter()
print(evens) # Output: [2, 4]
List comprehensions are preferred over map()
and filter()
in Python due to readability.
7. Recursion in Functional Programming
Functional programming favors recursion over loops.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Python has a recursion limit, so deep recursion can cause errors.
8. Decorators (Higher-Order Functions)
Decorators modify functions dynamically.
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def greet():
print("Hello!")
greet()
Decorators are a key feature of functional programming in Python.
9. Functional Programming vs. Object-Oriented Programming (OOP)
Feature | Functional Programming | Object-Oriented Programming |
---|---|---|
Main Focus | Functions & immutability | Objects & state management |
State Changes | Avoids modifying state | Modifies object attributes |
Functions | First-class citizens | Methods inside objects |
Looping | Uses map() , filter() , recursion | Uses for and while loops |
Example Languages | Haskell, Lisp, Python (supports both FP & OOP) | Java, C++, Python |