Is it possible to declare Ada range with unlimited upper bound?

☆樱花仙子☆ 提交于 2020-02-03 10:13:10

问题


I would like to declare a speed range for a record type in Ada. The following won't work, but is there a way to make it work?

   --Speed in knots, range 0 to unlimited
   Speed : float Range 0.0 .. unlimited ;

I just want a zero positive value for this number...


回答1:


You can't -- but since Speed is of type Float, its value can't exceed Float'Last anyway.

Speed : Float range 0.0 .. Float'Last;

(You'll likely want to declare an explicit type or subtype.)




回答2:


Just for completeness, you can also define your own basic float types rather than use one called Float which may or may not have the range you require.

For example, Float is defined somewhere in the compiler or RTS (Runtime System) sources, probably as type Float is digits 7; alongside type Long_Float is digits 15;, giving you 7 and 15 digits precision respectively.

You can define yours likewise to satisfy the precision and range your application requires. The philosophy is, state what you need (in range and precision), and let the compiler satisfy it most efficiently. This is programming in the problem domain, stating what you want - rather than in the solution domain, binding your program to what a specific machine or compiler supports.

The compiler will either use the next highest precision native float (usually IEEE 32-bit or 64-bit floats) or complain that it can't do that

(e.g. if you declare

type Extra_Long_Float is digits 33 range 0.0 .. Long_Float'Last * Long_Float'Last;
your compiler may complain if it doesn't support 128 bit floats.




回答3:


Unlimited isn't possible. It would require unlimited memory. I'm not aware of any platform that has that. It's possible to write a package that provides rational numbers as big as the available memory can handle (see PragmARC.Rational_Numbers in the PragmAda Reusable Components for an example), but that's probably not what you're interested in. You can declare your own type with the maximal precision supported by your compiler:

type Speed_Value_Base is digits System.Max_Digits;
subtype Speed_Value is Speed_Value_Base range 0.0 .. Speed_Value_Base'Last;
Speed : Speed_Value;

which is probably what you're after.



来源:https://stackoverflow.com/questions/47445162/is-it-possible-to-declare-ada-range-with-unlimited-upper-bound

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!