4 ms·
I actually dislike this solution, because it relies on tests, while this could easily be a compile-time error. Not sure I like that D promotes implicitly and t
by iFreilicht 4y ago
I actually dislike this solution, because it relies on tests, while this could easily be a compile-time error.
Not sure I like that D promotes implicitly and then complains about the result of the addition not being assignable to a `char`.
But in theory, every integer could just have the maximum range of values encoded in its type, and for every arithmetic operation the compiler could check if the maximum range of the integer type is exceeded.
You could set the range explicitly:
fn mult_col(color:u8<0..31>, factor:u8<0..8>): u8<0..248> { color*factor }
Or make the function generic over any range of inputs where the possible range of outputs provably fits the output type, which would be the default.
There are crates that add ranged integers as types, but I haven’t found them satisfactory to work with.