纯函数:“无副作用"吗?暗示“总是相同的输出,给定相同的输入"? [英] Pure Functions: Does "No Side Effects" Imply "Always Same Output, Given Same Input"?

查看:16
本文介绍了纯函数:“无副作用"吗?暗示“总是相同的输出,给定相同的输入"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义一个函数为pure的两个条件如下:

The two conditions that define a function as pure are as follows:

  1. 无副作用(即只允许更改本地范围)
  2. 给定相同的输入,总是返回相同的输出

如果第一个条件总是成立,那么第二个条件是否也有不成立的时候?

If the first condition is always true, are there any times the second condition is not true?

即真的只有第一个条件才有必要吗?

I.e. is it really only necessary with the first condition?

推荐答案

以下是一些不改变外部作用域但仍被视为不纯的反例:

Here are a few counterexamples that do not change the outer scope but are still considered impure:

  • function a() { return Date.now();}
  • function b() { return window.globalMutableVar;}
  • function c() { return document.getElementById("myInput").value;}
  • function d() { return Math.random();}(这确实改变了 PRNG,但不被认为是可观察的)
  • function a() { return Date.now(); }
  • function b() { return window.globalMutableVar; }
  • function c() { return document.getElementById("myInput").value; }
  • function d() { return Math.random(); } (which admittedly does change the PRNG, but is not considered observable)

访问非常量非局部变量足以违反第二个条件.

Accessing non-constant non-local variables is enough to be able to violate the second condition.

我一直认为纯度的两个条件是互补的:

I always think of the two conditions for purity as complementary:

  • 结果评估不得影响副状态
  • 评估结果不得受旁态影响

术语副作用仅指第一种,修改非-本地状态.然而,有时读取操作也被认为是副作用:当它们是操作并且也涉及写入时,即使它们的主要目的是访问一个值.例如,生成修改生成器内部状态的伪随机数、从提高读取位置的输入流中读取数据或从涉及进行测量"命令的外部传感器读取数据.

The term side effect only refers to the first, the function modifying the non-local state. However, sometimes read operations are considered as side effects as well: when they are operations and involve writing as well, even if their primary purpose is to access a value. Examples for that are generating a pseudo-random number that modifies the generator's internal state, reading from an input stream that advances the read position, or reading from an external sensor that involves a "take measurement" command.

这篇关于纯函数:“无副作用"吗?暗示“总是相同的输出,给定相同的输入"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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