Surobaki
Surobaki

Reputation: 177

How do you perform a check for safe type conversion?

To preface: I'm programming in the newest version (as of writing) of SPARK Ada with GNAT Community.

I've been looking over the internet for a simple solution for this but all results seem to point to the same answer that isn't working for me. I have a new type Digit defined as TYPE Digit IS new Integer range 0 .. 9. I'd like to safely convert Integer to Digit. For the sake of this conversion I've also created a range DigitRange defined as TYPE DigitRange IS range 0 .. 9. I'm attempting to perform this conversion by checking whether or not Digit is in the range (IF InputInteger IN DigitRange) but this raises an incompatible types compilation error.

I'm aware that the more ideal solution to achieve this is using subtypes but I'm not permitted to do that.

Thank you for your answers.

Upvotes: 5

Views: 359

Answers (2)

Jeffrey R. Carter
Jeffrey R. Carter

Reputation: 3358

As with many things in Ada, there are multiple ways to do this in Ada, and while the use of 'Pos is an excellent solution, it may be useful to see some others.

Since Digit is derived from Integer, their base types have the same range, so you can write

Digit'Base (X) in Digit

You can also define a subtype of Integer with the desired range and use it for the comparison

subtype Digit_Range is Integer range Digit'First .. Digit'Last;

X in Digit_Range

The right side of [not] in can also be a subtype definition, so you can also use

X in Integer range Digit'First .. Digit'Last

Upvotes: 2

Niklas Holsti
Niklas Holsti

Reputation: 2142

Applying Integer'Pos to the Integer value "converts" it to a "universal integer", which you can then test for inclusion in the range of any integer type:

   X : Integer;
   ...
   if Integer'Pos(X) in Digit then ...

Upvotes: 6

Related Questions