Typing on units
Erland Sommarskog
sommar at enea.se
Thu Mar 15 07:26:59 AEST 1990
Marvin Rubenstein (marv at ism780.UUCP) writes:
>I am unaware of any commonly available language that prevents this form of
>mistake. Look at the following:
>
> double distance;
> double time;
> double velocity;
>
> velocity = distance/time; /* this makes sense */
> velocity = distance+time; /* I mixed 'apples' and 'oranges' and produced
> a lemon :-) */
The program below contains the same error and does not compile.
I have edited the error messages to stay below 80 columns.
PROCEDURE Type_test IS
TYPE Meter IS NEW Float;
TYPE Seconds IS NEW Float;
TYPE Meter_per_seconds IS NEW Float;
x : Meter := 2.2;
s : Seconds := 3.3;
v : Meter_per_seconds;
FUNCTION "/"(x : Meter; s : Seconds) RETURN Meter_per_seconds IS
BEGIN
RETURN Meter_per_seconds(x) / Meter_per_seconds(s);
END "/";
BEGIN
v := x / s;
v := x + s;
--------^A
------------^B
--A:error: RM 3.3: base type of expression must be meter_per_seconds, line 5
--B:error: RM 3.3: base type of expression must be meter_per_seconds, line 5
END Type_test;
In order to get division to work we had to define a function for it.
In fact we have to define a function of a similar kind for every operation
we want to make. This is a lot of typing, on the other hand: it does
well document the rules at hand. Performance won't be an issue. In
the sample above, the subprogram would disappear rapidly in the hands
of the optimizer. Normally it would be part of a package, but you
would mention in it in the INLINE pragma.
--
Erland Sommarskog - ENEA Data, Stockholm - sommar at enea.se
More information about the Comp.lang.c
mailing list