[challenge] Bounded types
Philippe Sigaud
philippe.sigaud at gmail.com
Sun Oct 10 14:16:05 PDT 2010
Hi,
there is a long discussion about a date/time module on the Phobos mailing
list, and among other very interesting things, it was suggested to add a
Bounded template to Phobos. I'll extract this as a challenge to the D community.
Bounded takes a type, a min value and a max value and gives back a type that
can hold only values between min and max (tested at runtime). Otherwise, I
gather it throws an exception.
for example:
Bounded!(char, 'a','z') can only hold lowercase letters.
Bounded!(double, 0.0, 1.0) is a bit like a double, but can only hold doubles
between 0.0 and 1.0.
As you can see, an "open or closed for both ends" policy could be interesting
to add. In the previous example, is 1.0 a correct value?
Another policy could be if it internally uses 'alias this' or not, and if
opAssign is defined. That is, given
alias Bounded!(int, 0, 9) Digit;
Digit d;
int foo(int i) { return i*i;}
can you do:
d = 9;
or do you have to do:
d = Digit(9);
And can you call foo with d?
As for all type-wrapper templates, this raises issues already seen on typedef
threads: subtype, parallel type, totally distinct type?
The challenge is: implement Bounded.
Philippe
PS: clever (or perverse) readers may wonder what happens when Bounded uses a
type that has no obvious ordering. Like: Bounded!(int function(int), ...). In
that case, I suggest passing a ordering template that will test if a given
value is between min and max. The default would be BinaryFun!"a < b". Another
possibility is to restrict Bounded to types defining opCmp.
More information about the Digitalmars-d
mailing list