为什么提出例外是副作用? [英] Why is the raising of an exception a side effect?

查看:169
本文介绍了为什么提出例外是副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据副作用的维基百科条目,引发异常构成副作用。考虑这个简单的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.

现在,当你观察底部值并根据它做出决定时,你只会破坏参照透明度 - 这可能引入非确定性,因为可能抛出许多不同的异常,并且你可以不知道哪一个。因此,出于这个原因,捕获异常在Haskell中的 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屋!

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