Do you like bounded integrals?

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Thu Aug 25 11:06:13 PDT 2016


Update: I've taken a shot at adding bounds, see 
https://github.com/dlang/phobos/pull/4613/commits/bbdcea723e3dd98a979ae3f06a6786645647a778. 
Here are a few notes:

* The Hook API works nicely with built-in or custom hooks, so no change 
there was necessary.

* The constructor got quite a bit more complicated because it needs to 
evaluate statically the bounds, which in turn evaluate the constructor 
statically. My solution was to define minRep and maxRep as the built-in 
representations of the min and max, and use those inside the constructor.

* There's trouble about choosing between a conservative and a statically 
precise approach to bounds computation. The simplest example is 
computing -x where x has type Checked!int. The precise result type is 
Checked!(int, int.min + 1, int.max). (If x == int.min, attempting to 
evaluate -x aborts the program.) The precise type is technically 
correct, but I assume in practice it'll just create a lot of annoyance 
due to the fact that x and -x have "slightly" different types.

* It gets worse with binary operators. Implementing the precise limits 
is a mini-project of its own (akin to the VRP algorithms). Going 
conservative (as the current work does) is annoying in a different way - 
any binary operator loses the custom limits information that the user in 
all likelihood had carefully planted.

My decision following this experiment is to drop support for custom 
limits in Checked. The complexity/power balance is untenable.

However, the hooks should be reusable with a different artifact called e.g.:

struct Bounded(T, T min, T max, Hook);

That should do precise static bounds computation in all VRP glory and 
interact well with Checked so the two can be composed.


Andrei


More information about the Digitalmars-d mailing list