Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ada: Subtype Conversion or calling 'Base

I have the following -simple- problem: A delta-type for representation of degrees and a subtype of it, angles, where I limted the range from 0.0 .. <360.0. Now, I want to override the "+"-operator for the subtype to have my own modulo-operator:

package ...
type Degree is digits Degree_Digits;
end package

package ...
subtype Limited_Angle is Degree range Degree_Min .. Degree_Max;
function "+" (Left, Right : in Limited_Angle) return Limited_Angle;
end package

And the implementation:

function "+" (Left, Right : in Limited_Angle) return Limited_Angle is
    res : Degree;
begin
    res := Units.Base.Degrees."+"(Left, Right);
    ...
    return Limited_Angle(res);
end "+";

But I do not like the way, the +-operator is called. My first idea was to have something like

res := Degree(Left) + Degree(Right);

But this does not work. My compiler is warning about infinite recursion. Even the more strict:

res := (Degree(Left)) + (Degree(Right));

is warning about infinite recursion. And I do not understand the principle behind this. Shouldn't T(S) transform S to T? It can't be an optimization problem since (T(S)) does also not work.

Did I miss-understand the concept of type-subtype conversion (most probably) and does anyone have a solution/explanation? Or even a better solution?

Thanks!

like image 521
blauerreimers Avatar asked Aug 16 '18 21:08

blauerreimers


People also ask

What is a subtype in Ada?

A subtype is a type together with a constraint; a value is said to belong to a subtype of a given type if it belongs to the type and satisfies the constraint; the given type is called the base type of the subtype.

What are the types of Ada?

Language-Defined Types The principal scalar types predefined by Ada are Integer , Float , Boolean , and Character . These correspond to int , float , bool / boolean , and char , respectively.


1 Answers

Your problem isn't related to type conversion, but to understanding the difference between types and subtypes.

All subtypes of a type have exactly the same operations. The differences between subtypes of a type (including the type itself, technically the "first subtype of the type") is only the set of allowed values.

This means that all your conversions between Degrees and Limited_Degrees don't do much, and your call to Units.Base.Degrees."+" (Left, Right) is actually a recursive call.

I think the solution to your problem is to make Limited_Degrees a derived type, and not a subtype.

like image 179
Jacob Sparre Andersen Avatar answered Sep 23 '22 00:09

Jacob Sparre Andersen