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.
3. The C Veteran: Everything should be allowed. And when unsigned is
within a mile, the type is unsigned. I'll take care of the rest.
4. The Assembly Programmer: Use whatever type you want. The assembly
language operation for subtraction is the same.
5. The Dynamic Language Fan: Allow whatever and check it dynamically.
6. The Static Typing Nut: Use some scheme to magically weed out 73.56%
mistakes and disallow only 14.95% valid uses.
Your example is in fact perfect. It shows how the result of a
subtraction has ultimately its fate decided by case-by-case use, not
picked properly by a rule. The example perfectly underlines the
advantage of my scheme: the decision of how to type u1 - u2 is left to
the only entity able to account: the user of the operation. Of course
there remains the question, should all that be implicit or should the
user employ more syntax to specify what they want? I don't know.
Andrei