纯函数可以读取全局状态吗?
请注意:“纯”函数并不是指“纯虚拟”
我指的是 this
如果函数“读取”某些全局状态,是否会自动呈现它不纯洁? 还是取决于其他因素?
如果它自动使其变得不纯,请解释原因。
如果取决于其他因素,请解释它们是什么。
Please note: by a "pure" function, I don't mean "pure virtual"
I'm referring to this
If a function "reads" some global state, does that automatically render it impure? or does it depend on other factors?
If it automatically renders it impure, please explain why.
If it depends on other factors, please explain what are they.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
“纯”函数是其结果仅取决于其输入参数的函数。 如果它读取其他任何内容,则它不是纯函数。
A "pure" function is a function whose result depends only on its input arguments. If it reads anything else, it is not a pure function.
在某些特殊情况下,是的。 例如,如果您有一个已计算值的全局缓存,仅由您的函数读取和写入,那么它在数学上仍然是纯的,因为输出仅取决于输入,但它不会是纯的从最严格的意义上来说。 例如:
在这种情况下,只要没有其他函数接触全局缓存,它仍然是一个数学上的纯函数,即使它在技术上依赖于外部全局状态。 然而,这种状态只是一种性能优化——没有它它仍然会执行相同的计算,只是速度更慢。
In certain specialized instances, yes. For example, if you had a global cache of already-computed values that was only read and written by your function, it would still be mathematically pure, in the sense that the output only depended on the inputs, but it wouldn't be pure in the strictest sense. For example:
In this case, so long as no other function touches the global
cache
, it's still a mathematically pure function, even though it technically depends on external global state. However, this state is just a performance optimization -- it would still perform the same computation without it, just more slowly.所以,如果你的全球“状态”没有改变,那就没问题。
另请参阅引用透明度:
So, if your global 'state' doesn't change you are fine.
Also see referential transparency:
例如,在 Haskell 中,您可以在不纯的一侧创建一个无限的随机数列表,并将该列表传递给您的纯函数。 仅当需要时,实现才会生成纯函数正在使用的下一个数字,但该函数仍然是纯函数。
In Haskell for instance, you can create an endless list of random numbers on the impure side, and pass that list to your pure function. The implementation will generate the next number your pure function is using only when it needs it, but the function is still pure.