Previous topic | Next topic | Ada Home Page | Index

Derived Types

Motivation: Number Nonsense

INTEGER and FLOAT are mathematical concepts, but numbers mean things in the real world

Using pure numbers, we can write nonsense:

	age := -20;

	height := age - class_size;

	shoe_size := 2 * no_on_bus;

Types help program values reflect the real world.


Integer Types

New data types can be derived from INTEGER:

      type ages is new INTEGER range 0 .. 110;
      age : ages;
      voting_age : constant ages := 18;


      type heights is range 0 .. 230;
      height : heights;

      min_enrolment : constant :=   6;
      max_enrolment : constant := 200;
      type class_sizes is range 0..max_enrolment;

      class_size : class_sizes;

These types are distinct from each other, and from INTEGER.

Types cannot be mixed in Ada, so nonsense can be avoided.


FLOAT Types

Must specify precision, may specify range

Normal FLOAT operations, attributes.

Again, cannot mix types.


Type conversion

Ada has strong typing: different types cannot be mixed

Explicit type conversion is permitted:


   type length is digits 5 range 0.0 .. 1.0E10;
   type area   is digits 5 range 0.0 .. 1.0E20;

   function area_rectangle (L,H : length) return area is
   begin
      return area(L) * area(H);
   end;


Benefits of derived types

Nonsense rejected by compiler

	height := age - class_size;

"Out of range" rejected by compiler

	age := -20;

"Out of range" run time error

	class_size := class_size + 100;

Enforce distinct nature of different objects

Robust, elegant, effective programs


Previous topic | Next topic | Ada Home Page | Index
c-lokan@adfa.oz.au / 21 Feb 96