6.1. Enumeration type - JulTob/Ada GitHub Wiki

An enumeration type defines an ordered set of distinct enumeration literals, for example a list of states or an alphabet of characters.


declare
  type Colour is (Red, Amber, Green);
  type Fish is (Cod, Hake, Salmon);
  X, Y: Colour;
  A, B: Fish;
begin 
  X := Red; --legal
  Y := X;   --legal
  A := X;   --illegal
end Sqrt;

This fragment of program is a block which declares two enumeration types Colour and Fish, and two variables of each type, and then performs various assignments. The declarations of the types give the allowed values of the types. Thus the variable X can only take one of the three values Red, Amber or Green. The fundamental rule of strong typing is that we cannot assign a value of one type to a variable of a different type. So we cannot mix up colours and fishes and thus our (presumably accidental) attempt to assign the value of X to B is illegal and will be detected during compilation.

Other Examples of Enumeration declaration types:

type State_Type is ( Setting, Waiting, Processing, Stopping);
---------------------------------------------------------------
  type Day is (Monday, Tuesday, Wednesday, Thursday,
    Friday, Saturday, Sunday);
---------------------------------------------------------------
Type Bills is (one, two, five, ten, twenty, fifty, hundred);

Today: Day:= Friday;

Los tipos enumerados se definen enumerando la lista de valores literales del tipo (un valor literal enumerado puede ser un carácter literal o una secuencia de caracteres válida como identificador). El orden y la posición de los valores de un tipo enumerado vienen determinados por el orden en que se enumeran (al primer valor de la lista le corresponde el valor cero). Tipos enumerados distintos pueden definirse con literales iguales, cuando el uso de estos literales pueda resultar ambiguo se deberán cualificar con el nombre del tipo. Se pueden definir subtipos de un tipo enumerado especificando un rango de valores. La entrada/salida de valores de un tipo enumerado se realiza instanciando el paquete Ada.Text_IO.Enumeration_IO. A los tipos enumerados les son aplicables los atributos generales de los tipos escalares y, en particular, los atributos de los tipos discretos.

type Semana is (Lun, Mar, Mie, Jue, Vie, Sab, Dom);
type Dígito_Romano is ('I', 'V', 'X', 'L', 'C', 'D', 'M');
type Colores is (Rojo, Naranja, Amarillo, Verde, Azul Añil, Violeta);
type Semáforo is (Verde, Amarillo, Rojo);