Positive

Don nospam at nospam.com.au
Mon Oct 6 02:42:51 PDT 2008


Andrei Alexandrescu wrote:
> Hello,
> 
> 
> (Background: Walter has kindly allowed ".()" as an alternative to the 
> ugly "!()" for template argument specifications.)
> 
> Just a quick question - I am feeling an increasing desire to add a 
> template called Positive to std.typecons. Then Positive.(real) would 
> restrict its values to only positive real numbers etc.
> 
> The implementation would accept conversion from its base type, e.g. 
> Positive.(real) can be constructed from a real. The constructor enforces 
> dynamically the condition. Also, Positive.(real) accepts implicit 
> conversion to real (no checking necessary).
> 
> There are many places in which Positive can be useful, most notably 
> specifications of interfaces. For example:
> 
> Positive.(real) sqrt(Positive.(real) x);

 From the IEEE definition of sqrt(x), x can be >=0, which includes -0.
For negative zero, the return result is -0.
However, not all positive-valued functions will accept -0 as an 
argument. They also vary in whether or not they will accept an infinity 
or a NaN.
So there's an annoying bit of complication.


> These specifications are also efficient because checking for positivity 
> is done outside sqrt; if you had a Positive.(real) to start with, there 
> is no cascading checking necessary so there's one test less to do.
> 
> However, there is also the risk that Positive has the same fate the many 
> SafeInt implementation have had in C++: many defined them, nobody used 
> them. What do you think? If you had Positive in std and felt like 
> crunching some numbers, would you use it?

I think it probably is similar to SafeInt in C++. It just doesn't add 
enough value. Essentially, it allows you to drop some trivial contracts. 
But I don't think it scales particularly well. As math functions gain 
more arguments, the relationships in the 'in' contracts tend to get more 
complicated.

Much more useful would be positive int. Meaning, the top bit of the int 
is always 0, which is a completely different concept to uint. Then we 
could have implicit conversion from posint -> int and posint -> uint, 
and disallow conversions between int <-> uint.

But really I'd like to see polysemous types first...



More information about the Digitalmars-d mailing list