Idempotence

Idempotent operations only change their operand once. After the initial change, any follow-up application should leave the operand unchanged. Sorting and uppercasing the contents of the string are good examples of idempotent operations. Please note that the same operations had the length property invariant in the previous example.

We can demonstrate that operations toUpperCase and sorted are idempotent by applying them a different number of times and expecting that the result is the same as after the first application:

scala> forAll((a: String) => 
a.toUpperCase().toUpperCase() == a.toUpperCase()).check
+ OK, passed 100 tests.
scala> forAll((a: String) => a.sorted.sorted.sorted == a.sorted).check
+ OK, passed 100 tests.

For multiplications, the natural idempotent element is by definition the identity element. But it is also a zero:

scala> forAll((a: Int) => a * 0 * 0 == a * 0) .check
+ OK, passed 100 tests.

The logical AND and OR are idempotent for the Boolean values false and true, respectively.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.186.46