As a programmer, you will be quite familiar with the abs function. I thought I was. In fact it was filed in my brain drawer with the absolute mathematical function. It takes a number and provides an always positive or zero result. Right?
Well, mostly. This morning, while typing in the scala REPL:
res0: Int = -2147483648
What? Well, it makes sense at bit-level. Using two-complements representation for signed integers, 0 is considered positive so the negative values have an additional item located at the bottom. Once the size of the integer is fixed there is no way to represent the negation of the lowest integer in the range.
Apparently Scala documentation ignores this corner case, stating that abs always is greater than or equal to zero.
What about the other side of the Languages Pool?
int x = INT_MIN;
int absX = abs( x );
printf( "%d\n", absX );
Guess what… All in the same boat. This code prints INT_MIN which is pretty negative by my standards. Talking about standards, differently from what happens in the Scala world, ISO C specifications state that abs() triggers an undefined behavior in this case.
This is another pitfall when trying to make practical stuff representing abstract concepts. Some pitfalls are quite easy to spot – computer integers are not infinite as the natural numbers are; others are more subtle – computer floating point numbers are not Reals (and not even Rationals).
Lesson learned – know your tools and keep in mind that in theory, theory and practice are the same. In practice, they are not.