Positive

Alexander Pánek alexander.panek at brainsware.org
Sat Oct 4 21:26:19 PDT 2008


Andrei Alexandrescu wrote:
> There are many places in which Positive can be useful, most notably 
> specifications of interfaces. For example:
> 
> Positive.(real) sqrt(Positive.(real) x);

I think such restrictions/contracts are up to the implementation of an 
interface. There’s no point in defining them with interfaces, besides 
specific mathematical functions, which don’t play such big role in the 
“real world” as far as I can tell.

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

Same goes for contracts. It basically happens outside the body of the 
function, already.

> 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 wouldn’t, since I can’t seem to see the point of it — well, besides 
trying to express mathematical notations in D, which in turn I find 
pretty pointless..

> About contracts: Let me explain how I think that's inferior to Positive 
> in two ways.
> 
> 1. Enough functions are defined on positive numbers only, to justify 
> factoring that contract out of the functions themselves.

I don’t think that the amount of functions defined as such really 
justify such a kind of (additional) restriction option. Positivity can 
be asserted by only accepting positive (unsigned) primitive types and a 
null argument is asserted in a contract. Adding another layer of 
restriction doesn’t make it any better. Especially not if you only need 
it in a very specific set of functions.

> 2. The efficiency perk is that when using several such functions 
> together, there's only one check; once in Positive-land, no more checks 
> are necessary.

Speaking mathematically correct, you can’t really let sqrt return a 
signed, positive value, since every sqrt has two results — positive and 
negative. There’s no point in restricting the return type to positive 
and especially not signed values.



More information about the Digitalmars-d mailing list