Do you like bounded integrals?
Marco Leise via Digitalmars-d
digitalmars-d at puremagic.com
Mon Aug 29 08:33:42 PDT 2016
Am Tue, 23 Aug 2016 16:40:06 -0400
schrieb Andrei Alexandrescu <SeeWebsiteForEmail at erdani.org>:
> Currently checkedint (https://github.com/dlang/phobos/pull/4613) stands
> at 2432 lines and implements a variety of checking behaviors. At this
> point I just figured I can very easily add custom bounds, e.g. an int
> limited to 0 through 100 etc. It would take just a few lines because a
> lot of support is there (bounds hooks, custom min/max) anyway.
In Pascal/Delphi I used them often for day of the week,
percentages and anything else that is naturally bounded. I
guess as so often with "library features" it would depend on
some pull and push factors. "What module was it? What do I
have to set for 'Hook' again, so I can set 'min' and
'max'?" vs. "It's the proper type to use. It save me time here
by catching bugs."
> However, I fear it might complicate definition and just be a bit much.
> Here's the design I'm thinking of. Current:
>
> struct Checkedint(T, Hook = Abort);
>
> Under consideration:
>
> struct Checkedint(T, Hook = Abort, T min = T.min, T max = T.max);
>
> It's easy to take the limits into account, but then there are a few
> messes to mind:
>
> * When assigning a Checked to another, should the limits be matched
> statically or checked dynamically?
As for statically checking, "a = b" should work if b's range
is included in a's range, just like we can assign a ubyte to a
uint. Types with only a partial overlap should probably be
dealt with at runtime the same way assignments of normal ints
would be checked. As an upgrade to that one could also
statically check if the ranges have no overlap at all.
> * When composing, do the limits compose meaningfully?
You mean like when one multiplies two Checkedints ?
> * 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).
>
> 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?
>
>
> Andrei
I have no answer to that either. The following could make it
more accessible, much like the two Exception constructors we
have:
alias CheckedInt(T, T min, T max, Hook = Abort) =
CheckedIntImpl!(T, Hook, min, max);
alias CheckedInt(T, Hook = Abort) =
CheckedIntImpl!(T, Hook, T.min, T.max);
struct CheckedIntImpl(T, Hook = Abort, T min, T max);
--
Marco
More information about the Digitalmars-d
mailing list