Home > Article > Backend Development > What are the functional programming properties of C++ functions?
C supports functional programming features, including: Pure functions: declared with the const modifier, do not modify input or rely on external state. Immutability: Using the const keyword to declare a variable, its value cannot be modified. Lazy evaluation: Use the std::lazy function to create lazy values and lazily evaluate expressions. Recursion: A functional programming technique in which a function calls itself, using return to call itself.
Functional programming characteristics of C functions
Functional programming (FP) is a programming paradigm that emphasizes the use of pure functions , immutability, lazy evaluation and recursion. C supports FP features, including:
Pure functions
Pure functions do not modify their inputs and do not rely on external state. In C, pure functions can be declared with the const
modifier:
const int add(int x, int y) { return x + y; }
Immutability
Immutable objects cannot modify their values. In C, you can declare immutable variables using the const
keyword:
const int x = 5; x = 6; // 错误,不可变变量不能修改
Lazy evaluation
Lazy evaluation delays the evaluation of expressions, until its value is needed. In C, lazy values can be created using the std::make_lazy
function from the std::lazy
library:
std::lazy<int> x = std::make_lazy([] { return 5; }); std::cout << *x << "\n"; // 打印 5
Recursive
Recursion is a functional programming technique where the function calls itself. In C, a recursive function can be called by itself using the keyword return
:
int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); }
Practical case
The following code shows the FP feature in C Practical application:
#include <array> #include <iostream> #include <iterator> #include <numeric> int main() { // 纯函数:计算数组元素和 const auto sum = [](auto xs) { return std::accumulate(xs.begin(), xs.end(), 0); }; // 不可变数组 const std::array<int, 5> xs = {1, 2, 3, 4, 5}; // 惰性求值:惰性求值一个纯函数 std::lazy<int> sum_lazy = std::make_lazy([xs] { return sum(xs); }); // 递归:计算斐波那契数列 const auto fib = [](auto n) { return n == 0 ? 0 : (n == 1 ? 1 : fib(n - 1) + fib(n - 2)); }; // 输出值 std::cout << "数组和:" << *sum_lazy << "\n"; std::cout << "斐波那契数:" << fib(10) << "\n"; return 0; }
The above is the detailed content of What are the functional programming properties of C++ functions?. For more information, please follow other related articles on the PHP Chinese website!