در برنامه‌نویسی کامپیوتر، یک تابع سره یا خالص (به انگلیسی: Pure Function) یک تابع است که دارای ویژگی‌های زیر باشد:[۱][۲]

  1. هر دستور بازگشتی آن، با هر آرگومان که بگیرد، یکسان است. (مقدار بازگشتی، هیچ تغییری به وسیله متغیرهای محلی ایستا، متغیرهای غیر محلی، mutable reference argumentsو یا جریان‌های ورودی از دستگاه های ورودی/خروجی نمی‌کند).
  2. ارزیابی آن هیچ اثر جانبی ندارد. (در مقدار متغیرهای محلیِ ایستا، متغیرهای غیرمحلی و mutable reference arguments و یا جریان‌های ورودی/خروجی دگرگونی ایجاد نکند).

نمونه‌ها ویرایش

توابع سره ویرایش

نمونه‌های زیر از توابع سره C ++ هستند:

توابع ناسره ویرایش

توابع C ++ زیر به علت نقض ویژگی ۱، ناسره هستند:

  • به دلیل بازگشت تغیر با یک متغیر غیر محلی
int f() {
  return x;
}
  • به دلیل بازگشت دگرگونی با یک mutable reference argument
int f(int* x) {
  return *x;
}

توابع C ++ زیر به علت نقض ویژگی ۲، ناسره هستند:

  • به دلیل دگرگونی یک متغیر محلیِ استاتیک
void f() {
  static int x = 0;
  ++x;
}
  • به دلیل دگرگونی متغیر غیر محلی
void f() {
  ++x;
}
  • به دلیل دگرگونی یک mutable reference argument
void f(int* x) {
  ++*x;
}
  • به دلیل دگرگونی جریان خروجی
void f() {
  std::cout << "Hello, world!" << std::endl;
}

توابع C ++ زیر به علت نقض هر دو ویژگی ۱ و ۲، ناسره هستند:

  • به دلیل مقدار بازگشتی با یک متغیر ایستای محلی و دگرگونی یک متغیر ایستای محلی
int f() {
  static int x = 0;
  ++x;
  return x;
}

برای مطالعهٔ بیشتر ویرایش

منابع ویرایش

  1. Bartosz Milewski (2013). "Basics of Haskell". School of Haskell. FP Complete. Archived from the original on 27 October 2016. Retrieved 2018-07-13. Here are the fundamental properties of a pure function: 1. A function returns exactly the same result every time it's called with the same set of arguments. In other words a function has no state, nor can it access any external state. Every time you call it, it behaves like a newborn baby with blank memory and no knowledge of the external world. 2. A function has no side effects. Calling a function once is the same as calling it twice and discarding the result of the first call.
  2. Brian Lonsdorf (2015). "Professor Frisby's Mostly Adequate Guide to Functional Programming". GitBook. Archived from the original on 6 July 2019. Retrieved 2018-07-14. A pure function is a function that, given the same input, will always return the same output and does not have any observable side effect.

پیونهای خارجی ویرایش