Concepts of Programming Languages

(Sean Pound) #1

306 Chapter 6 Data Types


Ada program equivalent if they have the same element type but have subscript
ranges of 0..10 and 1..11? Are two enumeration types equivalent if they have
the same number of components but spell the literals differently?
Another difficulty with structure type equivalence is that it disallows dif-
ferentiating between types with the same structure. For example, consider the
following Ada-like declarations:

type Celsius = Float;
Fahrenheit = Float;

The types of variables of these two types are considered equivalent under
structure type equivalence, allowing them to be mixed in expressions, which is
surely undesirable in this case, considering the difference indicated by the type’s
names. In general, types with different names are likely to be abstractions of
different categories of problem values and should not be considered equivalent.
Ada uses a restrictive form of name type equivalence but provides two type
constructs, subtypes and derived types, that avoid the problems associated with
name type equivalence. A derived type is a new type that is based on some
previously defined type with which it is not equivalent, although it may have
identical structure. Derived types inherit all the properties of their parent types.
Consider the following example:

type Celsius is new Float;
type Fahrenheit is new Float;

The types of variables of these two derived types are not equivalent, although
their structures are identical. Furthermore, variables of both types are not type
equivalent with any other floating-point type. Literals are exempt from the
rule. A literal such as 3.0 has the type universal real and is type equivalent to
any floating-point type. Derived types can also include range constraints on the
parent type, while still inheriting all of the parent’s operations.
An Ada subtype is a possibly range-constrained version of an existing type.
A subtype is type equivalent with its parent type. For example, consider the
following declaration:

subtype Small_type is Integer range 0..99;

The type Small_type is equivalent to the type Integer.
Note that Ada’s derived types are very different from Ada’s subrange types.
For example, consider the following type declarations:

type Derived_Small_Int is new Integer range 1..100;
subtype Subrange_Small_Int is Integer range 1..100;

Variables of both types, Derived_Small_Int and Subrange_Small_Int,
have the same range of legal values and both inherit the operations of Integer.
Free download pdf