4 ms·
http://www.adaic.org/resources/add_content/standards/05aarm/html/AA-3-5-7.html http://www.adaic.org/resources/add_content/standards/05aarm/... Compile-time and
by Jtsummers 9y ago
http://www.adaic.org/resources/add_content/standards/05aarm/html/AA-3-5-7.html http://www.adaic.org/resources/add_content/standards/05aarm/...
Compile-time and run-time floating point numbers constrained by precision and range. It's been a long time so I'm just going to include the examples in that document:
type Coefficient is digits 10 range -1.0 .. 1.0;
type Real is digits 8;
type Mass is digits 7 range 0.0 .. 1.0E35;
subtype Probability is Real range 0.0 .. 1.0;
These will be checked (to the limits of the ability of the system) at compile-time, and by default enforced at run-time. You can disable the run-time checks if you want for the sake of performance. The compile-time checks will "fail" to detect things where computations beyond the compiler's ability to reason might produce an invalid value.
- hellofunk 9y agoCool, but I don't know much about Ada, and would like to see an example for a statically-typed "range checker" in a more mainstream language used actively today. C++ templates can do a lot of magical stuff at compile time but such techniques are well beyond the reach of most developers. I can't think of any typed language I've used or seen in active modern professional work where you could validate a value as part of a type at compile time.
- Jtsummers 9y agoNot without extra-compiler tooling like other static analysis tools, you're probably correct. I haven't had a chance to use much Ada, it's always been a pleasure for me to work in because I get to use things like the above to make my code so much clearer.
- mark-r 9y agoPascal has integer range types, but Pascal hasn't been mainstream for a long time now.
- Someone 9y agoI think you can get quite far in C++ with a class that has a constexpr constructor taking a double that checks for range, and (quite a few) operator overloads that allow one to do the normal operations on such quantities.
- Too 9y agoC# with "code contracts" allows you to annotate function arguments with valid ranges which will be statically checked at compile time. It's quite verbose though. https://docs.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts https://docs.microsoft.com/en-us/dotnet/framework/debug-trac...