I am looking to do a comparison of a string to and enumeration. I have written a sample code of what I am attempting. Since a String and and Enumerated type are different, how do I go about doing this properly in Ada?
WITH Ada.Text_IO; USE Ada.Text_IO;
PROCEDURE ColorTest IS
TYPE StopLightColor IS (red, yellow, green);
response : String (1 .. 10);
N : Integer;
BEGIN
Put("What color do you see on the stoplight? ");
Get_Line (response, N);
IF response IN StopLightColor THEN
Put_Line ("The stoplight is " & response(1..n));
END IF;
END ColorTest;
Answering your actual question:
Ada doesn't allow you to compare values of different types directly, but luckily there is a way to convert an enumerated type to a string, which always works.
For any enumerated type
T
there exists a function:which returns a string representation of the enumerated object passed to it.
Using that, you can declare a function, which compares a string and an enumerated type:
If you want to do a case-insensitive comparison, you could map both strings to lower case before comparing them:
First instantiate
Enumeration_IO
forStopLightColor
:Then you can do either of the following:
Use
Color_IO.Get
to read the value, catching anyData_Error
that arises, as shown here for a similar instance ofEnumeration_IO
.Use
Color_IO.Put
to obtain aString
for comparison toresponse
.As an aside,
Stoplight_Color
might be a more consistent style for the enumerated type's identifier.Another possibility: