User Defined Attributes
bearophile
bearophileHUGS at lycos.com
Tue Nov 13 14:55:53 PST 2012
Walter Bright:
> consider the type "int". Different modules impute different
> meanings into it all the time, and it doesn't cause terrible
> compatibility problems between modules.
The usage of naked basic types as int and double cause troubles.
Haskell programmers avoid some of them defining strong types like
this (this syntax also allows you to specify exactly what
operations you want to be allowed on this new type, with that
"deriving"):
newtype Angle = A Double
deriving (Eq, Ord, Num, Fractional)
Similarly you can also tell apart angles represented in degrees
from angles in radians, and avoid some bugs. (It's possible to
overdo this idea, and make the code too much fussy and not handy
to write, so you have to keep some balance and not use too many
new types).
A possible D syntax, using std.typecons.Typedef:
alias Angle = SubTypedef!(double, Eq, Ord, Num);
That equals to:
alias Angle = Typedef!(double, Subtype, Eq, Ord, Num);
Where Eq, etc, are pre-defined template mixins that implement
different operations, like equality, opCmp, etc, that Typedef
mixes in.
Bye,
bearophile
More information about the Digitalmars-d-announce
mailing list