且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是幂等运算?

更新时间:2023-11-30 17:54:28

在计算中,幂等运算是指如果使用相同的输入参数多次调用该幂等运算,则不会产生任何其他影响.例如,从集合中删除某项可以被认为是对该集合的幂等操作.

In computing, an idempotent operation is one that has no additional effect if it is called more than once with the same input parameters. For example, removing an item from a set can be considered an idempotent operation on the set.

在数学中,幂等运算是 f(f(x))= f(x)的运算.例如,abs()函数是幂等的,因为所有xabs(abs(x)) = abs(x).

In mathematics, an idempotent operation is one where f(f(x)) = f(x). For example, the abs() function is idempotent because abs(abs(x)) = abs(x) for all x.

可以通过考虑数学定义中的 x 表示对象的状态来协调这些稍有不同的定义,而 f 是可以使该对象发生变异的运算.例如,考虑 Python set 及其discard方法. discard方法从集合中删除一个元素,如果该元素不存在,则不执行任何操作.所以:

These slightly different definitions can be reconciled by considering that x in the mathematical definition represents the state of an object, and f is an operation that may mutate that object. For example, consider the Python set and its discard method. The discard method removes an element from a set, and does nothing if the element does not exist. So:

my_set.discard(x)

与两次执行相同的操作具有完全相同的效果:

has exactly the same effect as doing the same operation twice:

my_set.discard(x)
my_set.discard(x)

幂等操作通常用于网络协议的设计中,在该协议中,执行一项操作的请求被保证至少发生一次,但也可能发生不止一次.如果该操作是幂等的,则两次执行此操作不会有任何危害.

Idempotent operations are often used in the design of network protocols, where a request to perform an operation is guaranteed to happen at least once, but might also happen more than once. If the operation is idempotent, then there is no harm in performing the operation two or more times.

有关更多信息,请参见幂等上的Wikipedia文章.

See the Wikipedia article on idempotence for more information.

上面的答案以前有一些不正确和误导性的例子.以下注释是在2014年4月之前写的,是较旧的版本.