Philippe Sigaud:

> 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.

I think they are also named ranged types, they are quite useful to reduce the 
bug-count of programs, because when you use them, you are sure they are bounded 
in the specified interval. 

They are one of the original built-in features I have asked few years ago for 
D, but I think Walter answered something like they are a "failed language 
feature". I have used them and I have appreciated them a lot in Delphi, and I 
think they are the opposite of a failure.

Implementing them as library things instead of built-ins may give a bit worse 
syntax (and maybe a bit lower performance if assembly is used inside them, that 
kills inlining), but allows for more experiments and flexibility. But the 
"alias this" must be implemented really well by the compiler.


Their syntax in Pascal and Ada:
http://en.wikipedia.org/wiki/Pascal_%28programming_language%29#Subrange_types
http://en.wikipedia.org/wiki/Ada_%28programming_language%29#Data_types

In SPARK (Ada subset) you may also write (allows you to specify that it's a 
subtype):
subtype String_3_Index is Positive range 1 .. 3;


In D there's the ranged foreach syntax:
foreach (i; 0 .. 10)
If that 0 .. 10 syntax becomes more first class, it may be used to specify a 
bit better ranges for library-defined ranged types.


> Otherwise, I gather it throws an exception.

It's a to-be standard numeric overflow exception, I presume.
Or just asserts, or otherwise it must have a way to statically disable those 
bound tests.


> 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.

Be careful to avoid over-engineer them :-)

In the end bounded types are just a special case of numeric overflow tests (a 
difference is that your bounded values work with floating point values too), 
that I think still are very useful in D both for debugging and to create 
high-reliability D code (I think D may eventually interest people that write 
code that must be very safe, like code that controls potentially deadly 
machines).

Bye,
bearophile

Reply via email to