Tutorial - Enumerated Type

Enumerated Types

There are a number of cases where it would be useful to have a set of constants - consider the following :-

Const Number Spring = 1;
Const Number Summer = 2;
Const Number Autumn = 3;
Const Number Winter = 4;

Type SeasonArray = Number[Spring To Winter];

	SeasonArray rainfall;
	rainfall[Spring] := 20;
	Output rainfall;

This is fine - but what is to prevent someone doing :-

	rainfall[17] := 20;

Having the index as an unrestricted integer does not provide much protection.

The solution to this is the concept of the "enumerated type". This is a way of creating a fixed set of constants and allowing the programmer to declare variables that can only accept one of the specified values - and have the compiler enforce this restriction.

Defining Enumerated Types

The syntax for defining an enumerated type is :-

        emun_def    ::= identifier [ = text_expr ] [ = num_expr ]

        emun_type   ::= Type identifier = ( enum_def [[ , enum_def ]] ) ;

You can now do the following :-

Type Season = ( Spring, Summer, Autumn, Winter );
Type SeasonArray = Number[Season];

Now the array index has been limited to just the specific set of identifiers.

It is also possible to declare variables and function formal parameters to be an enumerated type.

Special For Loop Syntax

There is a special extension to the For loop syntax for stepping through an enumerated type - as illustrated below :-

Type Season = ( Spring, Summer, Autumn, Winter );
Type SeasonArray = Number[Season];

	SeasonArray rainfall = [100, 200, 10, 150], cumulative;
	Season s;
	Number total = 0;
	For s In Season Do
		total += rainfall[s];
		cumulative[s] := total;
	Output cumulative;

Had we been accessing a single array we could have uses an Over loop.

Setting Values

Internally the system will allocate a text value, the same as the identifier name, and a numeric value, starting at 1 and incrementing. These value are not accessed directly within the source code but they may be used when reading and writing values.

Type Season = ( Spring = "le printemps", Summer = "l'été", Autumn = "l'automne", Winter = "l'hiver");
[= . . . =]
	For s In Season Do
		Output s;
'le printemps'