Junior — Middle
Can you explain the basics of principles and approaches of functional programming?
sobes.tech AI
Answer from AI
Functional programming (FP) is a programming paradigm based on the use of functions as the main building blocks and avoiding changing state and side effects.
Main principles and approaches of FP:
- Pure functions: a function always returns the same result for the same inputs and does not modify external state.
- Immutability: data does not change after creation; instead, new copies are created with modifications.
- Higher-order functions: functions that accept other functions as arguments or return them.
- Recursion instead of loops: recursion is often used for repeating operations.
- Absence of side effects: functions should not modify external variables, files, databases, etc.
Example in C++ (using lambda functions):
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Higher-order function: passing a lambda to std::for_each
std::for_each(numbers.begin(), numbers.end(), [](int n) {
std::cout << n * 2 << " ";
});
return 0;
}
Here, we do not modify the original vector but simply apply a function to each element for output, which aligns with the ideas of a functional approach.