0

在阅读Pony 操作教程时,我注意到一些中缀运算符有部分和不安全的版本。来自 C#、Java、Python 和 JS/TS,我对它们的作用一无所知。

在 C# 中,有用于算术的checkedunchecked上下文。在一个checked块中,会导致溢出的数学运算会引发异常。不安全的操作员与此有关吗?

有人可以解释不安全和部分运营商吗?

4

1 回答 1

1

常规运算符,例如add/ +mod/%%等,将始终返回最合理的结果。这会导致某些结果,例如除以零等于 0。这是因为这些函数在数学上被认为是非部分的,这意味着对于每个输入,都有一个定义的输出;即使输出可能不寻常,例如溢出的加法,其结果小于输入。

然而,在某些情况下,为每个输入明确定义的结果并不是程序员想要的。这就是不安全和部分运营商的用武之地。

  1. 由于这些函数必须返回已定义的结果(参见上面的除以零示例),因此它们必须运行额外且昂贵的指令才能获得保证。运算符的unsafe版本删除了这些保证,并使用更快的 CPU 指令,这可能会为某些输入提供意外结果。当您知道您的输入无法达到某些条件(例如溢出、被零除)并且您希望您的代码挤出一些额外的性能时,这很有用。从 ¹ 中记录的add_unsafe/+~mod_unsafe/%%~运算符的定义trait Integer,例如:
  fun add_unsafe(y: A): A =>
    """
    Unsafe operation.
    If the operation overflows, the result is undefined.
    """

  fun mod_unsafe(y: A): A
    """
    Calculates the modulo of this number after floored division by `y`.

    Unsafe operation.
    If y is 0, the result is undefined.
    If the operation overflows, the result is undefined.
    """
  1. 或者,您可能希望检测这些条件,这些条件会在运行时在您的代码中返回数学上错误的结果,这意味着函数不会为每组输入返回一个值,因此是partial. 这些将引发您可以照常处理的错误。还阅读¹中的add_partial/+?mod_partial/%%?运算符的文档,我们发现:trait Integer
  fun add_partial(y: A): A ?
    """
    Add y to this number.

    If the operation overflows this function errors.
    """

  fun mod_partial(y: A): A ?
    """
    Calculates the modulo of this number and `y` after floored division (`fld`).
    The result has the sign of the divisor.

    If y is `0` or the operation overflows, this function errors.
    """

¹ 此 trait 由 Pony 中的所有整数类型实现,包括有符号和无符号。

于 2021-08-15T14:12:11.690 回答