这是纯函数吗? [英] Is this a pure function?
问题描述
大多数来源将纯函数定义为具有以下两个属性:
Most sources define a pure function as having the following two properties:
- 对于相同的参数,它的返回值是相同的.
- 它的评估没有副作用.
这是我关注的第一个条件.在大多数情况下,很容易判断.考虑以下 JavaScript 函数(如 this文章)
It is the first condition that concerns me. In most cases, it's easy to judge. Consider the following JavaScript functions (as shown in this article)
纯:
const add = (x, y) => x + y;
add(2, 4); // 6
不纯:
let x = 2;
const add = (y) => {
return x += y;
};
add(4); // x === 6 (the first time)
add(4); // x === 10 (the second time)
很容易看出,第二个函数将为后续调用提供不同的输出,从而违反了第一个条件.因此,它是不纯的.
It's easy to see that the 2nd function will give different outputs for subsequent calls, thereby violating the first condition. And hence, it's impure.
这部分我得到了.
现在,对于我的问题,请考虑将给定金额(以美元为单位)转换为欧元的函数:
Now, for my question, consider this function which converts a given amount in dollars to euros:
(编辑 - 在第一行使用 const
.之前无意中使用了 let
.)
(EDIT - Using const
in the first line. Used let
earlier inadvertently.)
const exchangeRate = fetchFromDatabase(); // evaluates to say 0.9 for today;
const dollarToEuro = (x) => {
return x * exchangeRate;
};
dollarToEuro(100) //90 today
dollarToEuro(100) //something else tomorrow
假设我们从数据库中获取汇率并且它每天都在变化.
Assume we fetch the exchange rate from a db and it changes every day.
现在,无论我今天调用这个函数多少次,它都会为输入100
提供相同的输出.但是,明天它可能会给我一个不同的输出.我不确定这是否违反了第一个条件.
Now, no matter how many times I call this function today, it will give me the same output for the input 100
. However, it might give me a different output tomorrow. I'm not sure if this violates the first condition or not.
IOW,函数本身不包含任何改变输入的逻辑,但它依赖于一个未来可能会改变的外部常量.在这种情况下,它绝对肯定会每天都在变化.在其他情况下,它可能会发生;可能不会.
IOW, the function itself doesn't contain any logic to mutate the input, but it relies on an external constant that might change in the future. In this case, it's absolutely certain it will change daily. In other cases, it might happen; it might not.
我们可以称这样的函数为纯函数吗?如果答案是否定的,那么我们如何将其重构为一?
Can we call such functions pure functions. If the answer is NO, how then can we refactor it to be one?
推荐答案
dollarToEuro
的返回值取决于一个不是参数的外部变量;因此,该函数是不纯的.
The dollarToEuro
's return value depends on an outside variable that is not an argument; therefore, the function is impure.
如果答案是否定的,那么我们如何将函数重构为纯函数?
If the answer is NO, how then can we refactor the function to be pure?
一种选择是传入exchangeRate
.这样,每次参数为 (something, somethingElse)
时,输出保证为 something * somethingElse
:
One option is to pass in exchangeRate
. This way, every time arguments are (something, somethingElse)
, the output is guaranteed to be something * somethingElse
:
const exchangeRate = fetchFromDatabase(); // evaluates to say 0.9 for today;
const dollarToEuro = (x, exchangeRate) => {
return x * exchangeRate;
};
请注意,对于函数式编程,应避免使用 let
- 始终使用 const
以避免重新分配.
Note that for functional programming, you should avoid let
- always use const
to avoid reassignment.
这篇关于这是纯函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!