Treating the abusive unsigned syndrome
Lars Kyllingstad
public at kyllingen.NOSPAMnet
Wed Nov 26 14:40:53 PST 2008
Andrei Alexandrescu wrote:
> Sean Kelly wrote:
>> Andrei Alexandrescu wrote:
>>>
>>> Notice that the fact that one operand is a literal does not solve all
>>> of the problems I mentioned. There is for example no progress in
>>> typing u1 - u2 appropriately.
>>
>> What /is/ the appropriate type here? For example:
>>
>> uint a = uint.max;
>> uint b = 0;
>> uint c = uint.max - 1;
>>
>> int x = a - b; // wrong, should be uint
>> uint y = c - a; // wrong, should be int
>>
>> I don't see any way to reliably produce a "safe" result at the
>> language level.
>
> There are several schools of thought (for the lack of a better phrase):
>
> 1. The Purist Mathematician: We want unsigned to approximate natural
> numbers, natural numbers aren't closed for subtraction, therefore u1 -
> u2 should be disallowed.
>
> 2. The Practical Mathematician: we want unsigned to approximate natural
> numbers and natural numbers aren't closed for subtraction but closed for
> a subset satisfying u1 >= u2. We can rely on the programmer to check the
> condition before, and fall back on modulo difference when the condition
> isn't satisfied. They'll understand.
How about 1.5, the Somewhat Practical but Still Purist Mathematician? He
(that would be me) would like integral types called nint and nlong (the
"n" standing for "natural"), which can hold numbers in the range (0,
int.max) and (0, long.max), respectively. Such types would have to be
stored as int/long, but the sign bit should be ignored/zero in all
calculations. Hence any nint/nlong would be implicitly castable to
int/long. Is this a possibility?
As you say, natural numbers aren't closed under subtraction, so
subtractions involving nint/nlong would have to yield an int/long
result. In fact, if n1 and n2 are nints, one would be certain that n1-n2
never goes out of the range of an int.
Thing is, whenever I use one of the unsigned types, it is because I need
to make sure I'm working with nonnegative numbers, not because I need to
work outside the ranges of the signed integral types. Other people
obviously have other needs, though, so I'm not saying "let's toss uint
and ulong out the window".
-Lars
More information about the Digitalmars-d
mailing list