Exception for printing negative numbers
peter_tanski at cox.net
Thu Feb 15 21:25:56 EST 2007
I don't know if any of you have been annoyed by the Exception handed
down for printing a negative number, but there are several solutions
to that. One I posted a little while ago on the Commentary
Cmm:Implementing Exception Handling page (http://hackage.haskell.org/
trac/ghc/wiki/Commentary/CmmExceptions). Another easier to implement
version would be this:
-- all of these should already be available
-- in libraries/base/GHC/Show.lhs
define a decent absolute value function that
does not require negation and can operate
without danger of overflow or underflow (i.e.,
the absolute value of -2147483648 cannot be
represented in an Int32.
in C, this would be:
#define WORDBITS (sizeof(uint32_t) * 8)
/* you want the shift to be signed for sign extension
to create the mask.
uint32_t abs_mask = (uint32_t)( x >> (WORDBITS - 1) );
return (uint32_t)( (x + abs_mask) ^ abs_mask );
abs_i32 :: Int32 -> Word32
abs_i32 x =
let abs_mask = ( fromIntegral (x `shiftR` 31) )::Word32
( ((fromIntegral x)::Word32) + abs_mask ) `xor` abs_mask
Just a thought from the Great Beyond. I am sorry I have not been
more help putting the next release together--I have a bit of the work
done on X11 types and may submit that soon when I can find the time.
Most of my efforts have been directed toward a decent Replacement
library, which is coming along.
More information about the Cvs-ghc