Xref: utzoo comp.lang.c:26914 comp.lang.misc:4455 Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!mcgill-vision!bloom-beacon!eru!luth!sunic!enea!sommar From: sommar@enea.se (Erland Sommarskog) Newsgroups: comp.lang.c,comp.lang.misc Subject: Typing on units Message-ID: <883@enea.se> Date: 14 Mar 90 21:26:59 GMT References: <39941@ism780c.isc.com> Followup-To: comp.lang.misc Organization: Enea Data AB, Sweden Lines: 48 Marvin Rubenstein (marv@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@enea.se