Functional programming is more about declaring what you want to happen, rather than how you want it to happen.
Example:
return clean_windows(add_gas(create_car()))
Python is not great for functional programming, but the example above illustrates the concept. Reasons python is not great for functional programming:
- Lack of immutability: Functional programming relies heavily on immutable data structures, whereas Python
- Limited support for tail call optimization: Functional programming often uses recursion as a primary control structure, but Python does not optimize for tail calls, which can lead to stack overflow errors for deep recursions.
- Mixed paradigms: Python is a multi-paradigm language that supports both imperative and object-oriented programming, which can lead to less emphasis on functional programming principles.
The key distinction in the example (relative to imperative programming), is that we never change the value of the car variable. Instead, we compose functions that return new values based on the input value.
Immutability
In functional programming, we strive to make data immutable. Once a data structure is created, it cannot be mutated. Instead, any modification needed creates a new data structure.
Immutable data is easier to think about and work with. When 10 different functions are mutating the same data structure, it can be hard to track what the current state is. With immutability, you always know that the data structure you have is exactly what it was when it was created.
Generally speaking, immutability means fewer bugs and more maintainable code.