Do you like bounded integrals?

Lodovico Giaretta via Digitalmars-d digitalmars-d at puremagic.com
Tue Aug 23 14:08:02 PDT 2016


On Tuesday, 23 August 2016 at 20:40:06 UTC, Andrei Alexandrescu 
wrote:
> * When assigning a Checked to another, should the limits be 
> matched statically or checked dynamically?

The ideal would be implicit cast allowed when widening, explicit 
required when narrowing. As I think we will have to settle for 
always explicit, I would say dynamic check. This of course opens 
the way to many customizations: an user may want to customize 
what happens when the range check fails. Another user may even 
want a switch to statically disallow narrowing conversions.

> * When composing, do the limits compose meaningfully?

Every layer should build on the limits exposed by the underlying 
layer, so I don't see what may go wrong.

> * How to negotiate when both the user of Checked and the Hook 
> need to customize the limits? (e.g. if you look at WithNaN it 
> needs to reserve a special value, thus limiting the 
> representable range).

The idea is that WithNaN will not see the limits of the 
underlying types, but the limits set by the user. How to do this, 
see below.

> I think all of these questions have answers, but I wanted to 
> gauge the interest in bounded checked integrals. Would the need 
> for them justify additional complications in the definition?

 From what I can see in my experience, saturation with custom 
min/max pops up once in a while in projects. So it's nice to 
have, even if it is a slight complication in the definition.

> Under consideration:
>
> struct Checkedint(T, Hook = Abort, T min = T.min, T max = 
> T.max);

Can I suggest a different approach? Different bounds implemented 
as a hook?

alias MyBoundedInt = CheckedInt!(int, WithBounds!(0, 42));

The WithBounds hook would only define min, max and opCast. It may 
have other optional parameters, like whether to statically 
disallow narrowing casts, or what to do if a narrowing cast is 
found impossible at runtime.

What do you think about this?


More information about the Digitalmars-d mailing list