[Haskell-cafe] abs minBound < (0 :: Int) && negate minBound == (minBound :: Int)

Richard A. O'Keefe ok at cs.otago.ac.nz
Mon Aug 19 02:04:56 CEST 2013


On 19/08/2013, at 3:38 AM, Nicolas Frisby wrote:

> The docs at
> 
>   http://www.haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:gcd
> 
> give a NB mentioning that (abs minBound == minBound) is possible for fixed-width types.

At least three ways to represent negative integers in binary have been used:
- twos-complement   (asymmetric, -INT_MIN == INT_MIN, abs can have a negative result)
- ones-complement    (symmetric, -INT_MIN == INT_MAX, abs is always non-negative)
- sign-and-magnitude (symmetric, -INT_MIN == INT_MAX, abs is always non-negative)

Having used a B6700 as an undergraduate, I still think sign-and-magnitude is the
only really safe-and-simple scheme.  However, twos-complement has conquered.

The argument for twos-complement, which always puzzled me, is that the other
systems have two ways to represent zero.  I never found this to be a problem,
not even for bitwise operations, on the B6700.  I *did* find "abs x < 0"
succeeding to be a pain in the posterior.  (The B6700 had two different tests:
'are these two numbers equal' and 'are these two bit patterns equal'.)

> Two questions:
> 
>   1) This behavior surprised me. Does it surprise enough people to include a warning in the Haddock for abs and negate?

We cannot expect everyone who uses Haskell to be familiar with
the eccentricities of popular hardware.  I think it's worth mentioning.

>   2) Is this a common behavior in other languages?

Yes.

> My tinkering with gcc suggests it does not support the value -2^63, but instead bottoms out at (-2^63+1).

Your tinkering was insufficient.

f% cat 2c.c
#include <stdio.h>
#include <limits.h>

int main(void) {
    printf("%d\n", INT_MIN + INT_MAX);
    return 0;
}
f% gcc 2c.c
f% a.out
-1

Oh wait.  You said "63", not "31".

Change the key line to

    printf("%lld\n", LLONG_MIN + LLONG_MAX);

LLONG_MIN is going to be -(2**63) on any SPARC, x86, x86-64,
Power(PC), Alpha, ARM, MIPS, or z/Series machine, and a host
of others.

> 
> Thanks.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe





More information about the Haskell-Cafe mailing list