Positive
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Sat Oct 4 19:35:57 PDT 2008
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);
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?
In order to get things really started, there's already been an exchange
with Walter on the matter. His reply was (I haven't asked for
permission, but I'm pretty sure he'd agree making it public):
==============
Honestly, I wouldn't use it. I'd rather have an in contract for sqrt
that asserts the argument is positive. Also, this opens the door to
Negative, NegativeOrZero, ZeroOrInfinity, Odd, Even, Prime,
SixOrFifteen, etc.
==============
My answer to that was:
==============
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.
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.
About proliferation of types: I don't think that follows at all. Math
found positive numbers special enough to dedicate them a special
notation (|R with subscript "+"). There's also a special notation for
nonzero real numbers (|R with superscript "*"). There is no special
notation for any of the sets you mentioned. That is bound to mean something.
==============
I'm interesting in further arguments. This feature is a numbers issue
(pun not intended), meaning it will be any good only if enough people
find it useful enough to actually use it in their own code and
libraries, therefore building momentum behind it.
Andrei
More information about the Digitalmars-d
mailing list