Many things are best described using words, not numbers.
Ada lets you define an enumeration type: a data type whose values are a collection of allowed words.
type days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
type colours is (white, red, yellow, green, brown, blue, pink, black);
type traffic_colours is (green, yellow, red);
type suits is (clubs, diamonds, hearts, spades);
The values in an enumeration type are ordered:
clubs < diamonds
white < pink
colours(green) > colours(red)
traffic_colours(green) < traffic_colours(red)
Note that the same words can be elements in different enumeration types, even in the same program. They are distinguished by reference to the type as well as the element. The last examples show how this is done.
Enumeration types have the following benefits:
An example program shows the use of enumeration types in a program that determines the effect of mixing primary colours.
etype'FIRST etype'LAST
etype'PRED(c) etype'SUCC(c)
etype'POS(c) etype'VAL(i)
For example:
type days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
days'FIRST is Mon
days'LAST is Sun
days'PRED(Wed) is Tue
days'SUCC(Wed) is Thu
days'POS(Wed) is 2
days'VAL(3) is Thu
You must ensure the result is legal. A CONSTRAINT_ERROR will occur at run-time otherwise. For example, days'SUCC(Sun) is illegal.
Can use enumerated types as selectors in case statements.
Can use enumerated types for parameters and result types in functions and procedures:
function next_day(this_day : week_days) return week_days is
begin -- next day
if this_day = sun then
-- relational comparison of an enumeration type
return Mon;
else
return week_days'SUCC( this_day );
-- attribute of an enumeration type
end if;
end next_day;
Comparisons:
if this_day in weekend_days then
PUT("Holiday");
end if;
Input/output:
WIDTH=>n width of output value
SET=>UPPER_CASE use uppercase output
SET=>LOWER_CASE use lowercase output