Search This Blog

Saturday, 1 November 2014

Enumerations and sets

It is sometimes useful to have a data structure that holds specific, related data values. For example, if a program is to perform a particular action for data pertaining to each day of the week, the following Pascal code might be used:

type Day is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)

Such a data type (which is also available in Ada, C, and C++) is called an enumeration because it enumerates, or “spells out” each and every value that the type can hold.

Once the enumeration is defined, a looping structure can be used to process all of its values, as in:

var Today: Day;

for Today: = Monday to Sunday do (some state-ments)

Pascal, C, and C++ do not allow the same item to be used in more than one enumeration in the same name space (area of reference). Ada, however, allows for “overloading” with multiple uses of the same name. In that case, however, the name must be qualified by specifying the enumeration to which it belongs, as in:

If Day = Days (‘Monday’) . . .

As far as the compiler is concerned, an enumeration value is actually a sequential integer. That is, Monday = 0, Tuesday = 1, and so on. Indeed, built-in data types such as Boolean are equivalent to enumerations (false = 0, true = 1) and in a sense the integer type itself is an enumeration consisting of 0, 1, 2, 3, . . . and their negative counterparts. Pascal also includes built-in functions to retrieve the pre-ceding value in the enumeration (pred), the following ele-ment (succ), or the numeric position of the current element (ord).

The main advantage of using explicit enumerations is that a constant such as “Monday” is more understandable to the program’s reader than the value 0. Enumerations are frequently used in C and C++ to specify a limited group of items such as flags indicating the state of device or file operation.


Unlike most other languages Pascal and Ada also allow for the definition of a subrange, which is a sequential por-tion of a previously defined enumeration. For example, once the Day type has been defined, an Ada program can define subranges such as:

subtype Weekdays is Days range Monday . . Friday;

subtype Weekend is Days range Saturday . . Sunday;

Sets

The set type (found only in Pascal and Ada) is similar to an enumeration except the order of the items is not significant. It is useful for checking to see whether the item being con-sidered belongs to a defined group. For example, instead of a program checking whether a character is a vowel as fol-lows:

if (char = ‘a’) or (char = ‘e’) or (char = ‘i’) or (char = ‘o’) or (char = ‘u’) . . .

the program can define:

type Vowels = (a, e, i, o, u); if char in Vowels . . .

No comments:

Post a Comment