Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Hàm thuần túy (Pure Function) trong C++

Pure function (hàm thuần túy) là hàm:

  1. Luôn trả về cùng kết quả cho cùng input (deterministic)
  2. Không có side effect: không sửa global state, không I/O, không modify argument
  3. Không phụ thuộc trạng thái bên ngoài

Ví dụ Pure Functions

  • sin(x), cos(x), sqrt(x), pow(x,y)
  • strlen(s), strcmp(s1,s2)
  • max(a,b), min(a,b), abs(x)
  • Hàm toán học, string processing không sửa đổi input

Ví dụ Impure Functions

  • rand() - trả về khác nhau mỗi lần
  • time() - phụ thuộc thời gian thực
  • printf() - side effect I/O
  • scanf() - I/O + modify argument
  • Hàm sửa global variable

Ví dụ minh họa

strlen() - Pure

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char str[] = "Rainbows are beautiful";
    cout << "String: " << str << endl;
    cout << "Length: " << strlen(str) << endl; // Luôn 22
    return 0;
}

Kết quả

String: Rainbows are beautiful
Length: 22

sqrt() - Pure

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int n = 9;
    cout << "sqrt(" << n << ") = " << sqrt(n) << endl; // Luôn 3
    return 0;
}

Kết quả

sqrt(9) = 3

Lợi ích của Pure Function

  • Dễ test: Không cần mock, setup state
  • Thread-safe: Không shared state → không race condition
  • Cacheable/Memoizable: Kết quả có thể lưu lại cho cùng input
  • Parallelizable: Gọi song song an toàn
  • Reasoning dễ dàng: Chỉ nhìn signature là hiểu behavior
  • Compiler optimization: Constexpr, loop invariant code motion

Viết Pure Function trong C++

// Pure: chỉ dùng tham số, không sửa global, không I/O
int add(int a, int b) { return a + b; }

// Impure: sửa global
int counter = 0;
int impureAdd(int a) { return a + counter++; }

// Pure version của counter
int pureAdd(int a, int counter) { return a + counter; }

// C++11: constexpr function (compile-time pure)
constexpr int factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}
// factorial(5) tính tại compile time

Functional Programming trong C++

#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector v = {1,2,3,4,5};
    
    // Transform pure: không sửa v, tạo vector mới
    std::vector doubled;
    std::transform(v.begin(), v.end(), std::back_inserter(doubled),
        [](int x) { return x * 2; }); // Pure lambda
    
    // Accumulate pure
    int sum = std::accumulate(v.begin(), v.end(), 0,
        [](int a, int b) { return a + b; }); // Pure
    
    return 0;
}

Tóm tắt

Đặc điểmPure FunctionImpure Function
Same input → Same outputLuônKhông đảm bảo
Side effectsKhôngCó thể có
Depends on external stateKhôngCó thể
Thread-safeTự nhiênCần synchronization
TestableRất dễKhó (cần mock)