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

Declaring Subtypes

Sometimes an existing class may offer the functionality and behaviour you need, but it is useful to give the class a new name to identify the type of information being stored.

You can declare the new name like this:

  class ExamScore ^= int;

(Remember? the symbol ^= reads is defined as - see Symbols).

Often the range of values supported by the existing class is more than you need. For example, it might be that an exam score cannot be negative and cannot exceed 100. This is a constraint.

You can incorporate a constraint in your definition like this:

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

which can be read as

Class "ExamScore" is defined as those x of type int such that x lies between 0 and 100 inclusive.

Type constraints are not limited to simple range constraints. For example, if exam scores are always even numbers, you can declare:

  class ExamScore ^= those e: int :- 0 <= e <= 100 & (e % 2) = 0;

Using the definition of the enumeration class Color given earlier, you could declare a class for representing the colours of traffic light bulbs like this:

  class LightBulbColor ^= those x: Color :- x in set of Color {red@Color, yellow@Color, green@Color};

which reads

Class "LightBulbColor" is defined as those x of type Color such that x is in the set of Color constructed from values red, yellow and green

The Perfect language includes the following built-in type definitions:

 class nat ^= those x: int :- x >= 0;
 class string ^= seq of char;

switched-on lamp You should use nat instead of int to declare any variable (or parameter, or return type) that you know can never be negative, because the more information you give to Perfect Developer, the more it can help you.

The pseudonym string is provided merely as a convenience. It reads more naturally than seq of char and is quicker to type)

Knowledge round-up quiz

Next:  United Types

 

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.