Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Pure Function ใน C++

Pure Function ส่งคืนผลลัพธ์เดียวกันสำหรับ Input เดียวกันเสมอ ไม่มี Side Effects (ไม่แก้ไข Argument, ไม่ I/O, ไม่แก้ Global State)

Pure Functions ตัวอย่าง

  • sin(), sqrt(), strlen(), max(), pow(), floor()

Impure Functions ตัวอย่าง

  • rand() (ส่งคืนค่าต่างกันทุกครั้ง)
  • time() (ขึ้นกับเวลาจริง)
  • ฟังก์ชันที่แก้ไข Global Variable หรือทำ I/O

ตัวอย่าง strlen()

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

int main() {
    char str[] = "Rainbows are beautiful";
    cout << "The string is " << str << endl;
    cout << "The length of the string is " << strlen(str);
    return 0;
}

ผลลัพธ์

The string is Rainbows are beautiful
The length of the string is 22

ตัวอย่าง sqrt()

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

int main() {
    int num = 9;
    cout << "Square root of " << num << " is " << sqrt(num);
    return 0;
}

ผลลัพธ์

Square root of 9 is 3

ประโยชน์ของ Pure Functions

  • Testable − ทดสอบง่าย ไม่ต้อง Setup State
  • Cacheable − Memoization ได้ (Pure Function + Same Input = Same Output)
  • Parallelizable − รันพร้อมกันได้ปลอดภัย (No Shared State)
  • Reasonable − เข้าใจง่าย Debugง่าย

ใน Modern C++ ใช้ constexpr สำหรับ Compile-time Pure Functions