为什么提出例外是副作用? [英] Why is the raising of an exception a side effect?
问题描述
根据副作用的维基百科条目,引发异常构成副作用。考虑这个简单的python函数:
According to the wikipedia entry for side effect, raising an exception constitutes a side effect. Consider this simple python function:
def foo(arg):
if not arg:
raise ValueError('arg cannot be None')
else:
return 10
调用它与 foo(None)
总是会遇到一个异常。相同的输入,相同的输出。它是透明的。为什么这不是一个纯粹的功能?
Invoking it with foo(None)
will always be met with an exception. Same input, same output. It is referentially transparent. Why is this not a pure function?
推荐答案
纯度只有在观察到异常时才会被违反,并根据它做出决定这改变了控制流程。实际上,抛出一个异常值是透明的 - 它在语义上等同于非终止或其他所谓的最低值。
Purity is only violated if you observe the exception, and make a decision based on it that changes the control flow. Actually throwing an exception value is referentially transparent -- it is semantically equivalent to non-termination or other so-called bottom values.
如果(纯粹)函数不是总计 ,那么它评估为最低值。你如何编码最低值取决于实现 - 它可能是一个例外;或者不终止,或者除以零或者其他一些失败。
If a (pure) function is not total, then it evaluates to a bottom value. How you encode the bottom value is up to the implementation - it could be an exception; or non-termination, or dividing by zero, or some other failure.
考虑纯函数:
Consider the pure function:
f :: Int -> Int
f 0 = 1
f 1 = 2
这并非全部定义投入。对于一些它评估到底。该实现通过抛出异常来对其进行编码。它应该在语义上等同于使用 Maybe
或 Option
类型。
This is not defined for all inputs. For some it evaluates to bottom. The implementation encodes this by throwing an exception. It should be semantically equivalent to using a Maybe
or Option
type.
现在,当你观察 IO
monad中,同时生成所谓的伪装例外可以纯粹完成。
Now, you only break referential transparency when you observe the bottom value, and make decisions based on it -- which could introduce non-determinism as many different exceptions may be thrown, and you can't know which one. So for this reason catching exceptions is in the IO
monad in Haskell, while generating so-called "imprecise" exceptions can be done purely.
所以它不是真的提出例外是一个副作用。这是你是否可以根据一个例外值来修改纯函数的行为 - 因此打破了参照透明度 - 这是问题。
So it is just not true that raising an exception is a side effect as such. It is whether or not you can modify the behavior of a pure function based on an exceptional value -- thus breaking referential transparency -- that is the issue.
这篇关于为什么提出例外是副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!