纯净和不纯的功能之间的区别? [英] Difference between pure and impure function?

查看:203
本文介绍了纯净和不纯的功能之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我假设纯函数必须始终具有返回类型(即,不能 void )并且必须具有相同的输出,而不管对象的状态和Impure函数改变对象的状态或打印对象的状态。

I assumed that pure functions must always have a return type (i.e., must not be void) and must have the same output regardless of the state of the object and that Impure functions change the state of the object or print the state of the object.

但我使用的教科书指出:

But the textbook I use states that:


访问器通常包含一个return语句,但是打印有关对象状态信息的方法也可以归类为访问者。

An accessor usually contains a return statement, but a method that prints information about an objects state may also be classified as an accessor.

我很困惑。哪一个是正确的?

I'm confused. Which one is correct?

编辑

有点澄清,事情让我问的是这个问题:

A bit of clarification,The thing that makes me ask is this question:

最后一个问题是给出使用的功能类型,并且那里评论的人表示它是一个不纯的功能,因为它正在打印。

The last question is to "Give the type of function used", and the people who commented there stated that it is an impure function as it is printing.

这个函数是纯粹还是不纯?

So is this function pure or impure?

推荐答案

内容取自此链接

纯函数的特征:


  1. 纯函数的返回值完全取决于它的参数
    因此,如果用相同的集合调用纯函数对于参数,您将始终获得相同的返回值。

  1. The return value of the pure func­tions solely depends on its arguments Hence, if you call the pure func­tions with the same set of argu­ments, you will always get the same return values.

它们没有任何副作用,如网络或数据库调用

They do not have any side effects like net­work or data­base calls

Impure函数的特征


  1. 不纯函数的返回值不仅仅取决于它的参数
    因此,如果你打电话使用相同参数集的不纯函数,您可能会获得不同的返回值
    进行考试ple,Math.random(),Date.now()

  1. The return value of the impure func­tions does not solely depend on its arguments Hence, if you call the impure func­tions with the same set of argu­ments, you might get the dif­fer­ent return values For exam­ple, Math.random(), Date.now()

它们可能有任何副作用,如网络或数据库调用

They may have any side effects like net­work or data­base calls

他们可以修改传递给他们的参数

They may mod­ify the argu­ments which are passed to them

function impureFunc(value){
  return Math.random() * value;
}

function pureFunc(value){
  return value * value;
}

var impureOutput = [];
for(var i = 0; i < 5; i++){
   impureOutput.push(impureFunc(5));
}

var pureOutput = [];
for(var i = 0; i < 5; i++){
   pureOutput.push(pureFunc(5));
}

console.log("Impure result: " + impureOutput); // result is inconsistent however input is same. 

console.log("Pure result: " + pureOutput); // result is consistent with same input

这篇关于纯净和不纯的功能之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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