Perfect Developer basic tutorial 3 This page last modified 2011-10-29 (JAC)

United Types

Sometimes you may need to declare an entity whose precise type may depend on how the program executes, or which may even vary during program execution.

For example, a function to return the balance of a customer account might normally return an integer, but if it fails for any reason (e.g. account unknown, or server inaccessible), it might instead return a string giving the reason for failure. You can represent the type of such an entity by a union, like this:

 int || string

If you expect to use this type for declaring several entities, it may be wise to give it a name, as you learnt to do in the last lesson:

 class BalanceOrReason ^= int || string;

Although united types (or variant records in some languages) are commonly needed in procedural languages, object-oriented software engineers rarely use them, because it is usually better to declare a class hierarchy instead. However, in Perfect there is a special case which is frequently needed: uniting a type with void. Recall that type void has a single value called null. So by uniting a type with void, you have the option of supplying either a value of that type, or no value at all (i.e. null).

For example, suppose a class of students sits an examination and you wish to record the results. If some of the students are unable to sit the examination due to illness, it seems unfair to give them a score of zero, so you wish to indicate instead that no result is available. If exam scores are integers in the range 0 to 100, you might declare the following:

 class RealExamScore ^= those x: int :- 0 <= x <= 100;

Then you can represent a single examination result (allowing for the possibility that the examination was not taken) as a value of type RealExamScore || void, and you can store the anonymized collection of student exam scores as a

 bag of (RealExamScore || void).

If you also declare:

 class ExamScore ^= RealExamScore || void;

then you should use type ExamScore when declaring a single result, and type bag of ExamScore when declaring the collection.

Note that the type union operator || has a very low precedence; so if you use a united type after the of keyword, you need to enclose it in brackets. In other words, bag of RealExamScore || void (without brackets) means the same as (bag of RealExamScore) || void.

Next:  Type Conversions and Enquiries

 

Save My Place Glossary Language Reference Manual
Tutorials Overview Main site   
Copyright © 1997-2012 Escher Technologies Limited. All rights reserved. Information is subject to change without notice.