什么是纯函数? [英] What is a pure function?

查看:158
本文介绍了什么是纯函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个报价:



  1. 预测纯功能。

谓词纯度:谓词是一个函数对象,返回是/否答案,通常为 bool 值。一个函数在
中是纯粹的数学意义,如果它的结果​​只取决于它的参数
(注意,这个pure的使用与纯虚函数
函数无关)。

Predicate purity: A predicate is a function object that returns a yes/no answer, typically as a bool value. A function is pure in the mathematical sense if its results depend only on its arguments (note that this use of "pure" has nothing to do with pure virtual functions).

不允许谓词保存或访问影响其运算符()的结果
的状态,包括成员状态和全局状态。

谓词(参见第15项)添加 operator()一个 const 成员函数。

Don't allow predicates to hold or access state that affects the result of their operator(), including both member and global state. Prefer to make operator() a const member function for predicatse (see Item 15).

这句话中提到的纯函数是什么?提前感谢。

What is a pure function as referred to in this statement and can someone provide examples? Thanks in advance.

推荐答案

这是一个纯函数:

int foo(int n)
{
  return n*2;
}

调用它的结果只取决于它的参数。

The result of calling it depends only on its argument.

这不是一个纯函数:

int i = 42;

int bar(int n)
{
  ++i;
  return n*i;
}

返回值取决于参数之外的其他事项。

The returned value depends on things other than the parameter.

这篇关于什么是纯函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆