Checking name equivalence
. Consider following declarations
type link = ^cell;
var next, last : link;
p, q, r : ^cell;
. Do the variables next, last, p, q and r have identical types ?
. Type expressions have names and names appear in type expressions.
. Name equivalence views each type name as a distinct type
. Type expressions are name equivalent iff they are identical
Name equivalence .
variable |
type expression
|
next |
link
|
last |
link
|
p |
pointer(cell)
|
q |
pointer(cell)
|
r |
pointer(cell)
|
. Under name equivalence next = last and p = q = r , however, next≠ p
. Under structural equivalence all the variables are of the same type
. Some compilers allow type expressions to have names.
. However, some compilers assign implicit type names to each declared identifier in the list of variables.
. Consider
type link |
= ^ cell;
|
|
: link;
|
|
: link;
|
p : |
^ cell;
|
q : |
^ cell;
|
r : |
^ cell; |
. In this case type expression of p, q and r are given different names and therefore, those are not of the same type
The code is similar to
type link = ^ cell
np = ^ cell;
nq = ^ cell;
nr = ^ cell;
var next : link;
last : link;
p : np;
q : nq;
r : nr;
Name Equivalence: Some languages allow named types by the type construct or some thing similar.
This situation can be modeled by allowing type expressions to have names. Name equivalence views each name to be of distinct type. This type system is a stronger type system because structurally different types are guaranteed to have different names. However structurally same types can have different names as seen in the example.
Having a Name Equivalent type system has its own advantages. For example, one may operate an account having multiple currency types each with an integer denomination. Thus his data will look like:
int rupees;
int dollars;
int euro;
. . .
Now consider what happens when we accidentally add dollar with rupee using the
normal "+" operator. The Structurally Equivalent type system will allow this as both the operands are integers.
In a Name Equivalent system we define types for each currency. For example,
Type t_rupee = int;
Type t_dollar = int;
Type t_eur0 = int;
Now the data looks like this:
t_rupee rupee;
t_dollar dollar;
t_euro euro;
Now we can specify special operators/functions to add a rupee type and a dollar type and avoid error like the above.
t_rupee addDollarToRupee(t_rupee rs, t_dollar ds)
{
return(rs + 40*ds); //Assuming the exchange rate is 40 rs/dollar.
}
Later when we study operator overloading we will see how "+" can be overloaded to add dollars and rupees.
|