More on Types
A Little Type Theory
What is a Type?
- A type is considered to have two parts:
- Set of values
- Set of operations
- Example: Integers
- Values: all integers from Integer'First to Integer'Last
- Operations:
- Arithmetic: +, -, *, /, **, abs
- Declare/Allocation
- I/O
- Attributes: Integer'Image, Integer'First
- Example: Days
- Values: Sunday, Monday, ..., Saturday
- Operations:
- Declare/Allocation - eg d: Day
- I/O - Create new IO package
- Attributes: Day'Image, Day'First, Day'Succ
Creating New Types
- When creating a new type, remember the values and operations
- Each kind of type has a way of specifying the values
- type Color is (red, blue, green);
- type Temperature is range 0 .. 100;
- type minutes is mod 60;
- Operations have several sources:
- Many are provided automatically
- Color'succ
- For numeric types the operations are inherited from the underlying type
- Operations can also be defined by user
Benefits of Defining New Types
Benefits of Defining New Types
- Program at level of problem vs level of machine
- Extend language to make it more expressive
- Abstraction
- Reliability:
- Stronger type checking
- Easier to validate input
- Errors detected earlier
- More readable
- One of the most important features of a language is its type system