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

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

问题描述

将函数定义为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 result evaluation must not have effects on side state
  • the evaluation result must not be affected by side state

术语副作用仅指第一个,该函数修改了非-本地状态.但是,有时读操作也被视为副作用:当它们是 operation 且还涉及写操作时,即使其主要目的是访问值.例如,生成伪随机数来修改发生器的内部状态,从推进读取位置的输入流中进行读取,或者从涉及获取测量"命令的外部传感器中进行读取.

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天全站免登陆