Download presentation
Presentation is loading. Please wait.
1
ada-typesI- 1 Ada95: A brief History 1975-1979: strawman-steelman requirements, Pascal is base 1975-1979: strawman-steelman requirements, Pascal is base 1981 : Green wins, becomes preliminary Ada 1981 : Green wins, becomes preliminary Ada 1983 : ANSI Standard, first validated compiler 1983 : ANSI Standard, first validated compiler 1987 : ISO Standard 1987 : ISO Standard 1990-1994 : Revision Process 1990-1994 : Revision Process 1995 : ANSI - ISO Ada 95 Standard 1995 : ANSI - ISO Ada 95 Standard 1995 : First validated GNAT compiler 1995 : First validated GNAT compiler
2
ada-typesI- 2 Design principles (Why Ada?) Software Engineering: programming in the large Readability over writability Rigorous standard for portability Precise semantics Built-in concurrency Strong-Typing: all unsafe code is explicit
3
ada-typesI- 3 Ada, C++ and Java Big, capable languages strong typing : Ada, C++, Java Generics : Ada C++ Concurrency : Ada Java Packages: Ada C++ and Java Ahead of its time in design Out of step in implementation Between language generations
4
ada-typesI- 4 Key Goals Readability : wordy but readable strong typing : find errors when you compile, don’t debug Programming in the large: package it and offer interfaces Exception Handling: Expect errors, deal with them. Data abstraction : apples are not oranges (user defined types will not be set to equal without casting) Object orientation : Inheritance and late binding Tasking : walk, chew gum, etc. (I.e. threads) Generic units : similar functionality across different types
5
ada-typesI- 5 The canonical example with Text_Io; use Text_Io; procedure example is -- Does not have to be called “main” begin Put_Line (“easier than we thought!”); end;
6
ada-typesI- 6 A small package interface Package Math_Functions is -- Here we are defining the interfaces function Sqrt (X : Float) return Float; function Exp (Base : Float; Exponent : Float) return Float; end Math_Functions;
7
ada-typesI- 7 Using the package with Math_Functions; with Gnat_IO; use Gnat_IO; procedure Example2 is Val : Float; begin get (Val); put (“Sqrt (“); put (Val); put (“) = “); put (Math_Functions.Sqrt (Val)); new_line; end;
8
ada-typesI- 8 Dissection of this package Package body Math_Functions is -- Separately compiled unit Epsilon : constant := 1.0e-7; -- Declared variable function Sqrt (X : Float) return Float is -- functions have in params and ret Result : Float := X / 2.0; -- initialize a variable. begin while abs (Result * Result - X ) > Epsilon loop Result := 0.5 * (X / Result + Result); -- X/Result = Result if done end loop; return Result; end Sqrt;... end Math_Functions; -- Could be many functions here.
9
ada-typesI- 9 Summary of Package Features Package has data and functions. It can be accessed by writing “with” (and avoid qualifying by writing “use”). A full program is normally a bunch of packages together with a “main” procedure (lexically a subprogram) that starts the program. Define the interface by giving the signatures (types in and out), also known as the specification or declaration, and then define the body separately (and privately). Functions have in parameters and a return value. Procedures can have in, out or in out parameters. While loop is a nice way of programming this.
10
ada-typesI- 10 Packages and Compilation The compiler compiles one or more compilation units (compiler is not obligated to compile more than one at a time). These start with “with” and “use” clauses and then proceed to either a package declaration, a package body, a subprogram declaration, or a subprogram body.
11
ada-typesI- 11 A larger package interface (visible part) (p. 28 of Barnes) Package Buffer_System is -- Here we are defining the interfaces type Buffer is private; -- Means insides are inaccessible to other packages procedure Load (B : out Buffer; S : in String); procedure Get (B : in out Buffer; C: out Character) ; -- in out because Buffer is changed by the Get. private Max: constant Integer: = 80 ; type Buffer is record Data: String(1..Max); Start: Integer:= 1; Finish: Integer:= 0; end record; end Buffer_System;
12
ada-typesI- 12 Body of Buffer (repeats declarations) Package body Buffer_System is -- Separately compiled unit procedure Load(B: out Buffer; S: in String) is Begin B.Start := 1; B.Finish := S’Length; B.Data(B.Start.. B.Finish):= S; end Load;... end Buffer_System; -- Could be many functions here.
13
ada-typesI- 13 Using the Buffer as a Type My_Buffer: Buffer; -- declare a variable of type Buffer Load(My_Buffer, Some_String); Get(My_Buffer, A_Character); -- Key point. Given a package, can declare variables of types -- in the package (e.g. package is Buffer_System; declare object -- of type Buffer). -- Package is like a C++ library.
14
ada-typesI- 14 Access Types (Pointer) Typed pointers, for type safety and to minimize aliasing. Want to be sure that a pointer points to a single type (at least for now): type Handle is access Buffer; Ptr : Handle := new Buffer; Ptr.all is a Buffer. – could be an argument to a copy constructor Can write Ptr.Start, Ptr.Data, etc.
15
ada-typesI- 15 Enumeration Types (for colors, days of weeks etc.) Simplest Implementation: literals are mapped into successive integers Very common abstraction: list of names, properties Expressive of real-world domain, hides machine representation type suit is (hearts, diamonds, spades, clubs) ; type direction is (east, west, north, south, lost); Order of list implies that spades > hearts, etc.
16
ada-typesI- 16 Enumeration types and strong typing type Fruit is (Apple, Orange, Grape, Apricot); type Vendor is (Apple, IBM, Hewlett Packard); My_PC : Vendor; Dessert : Fruit; … My_PC := Apple; Dessert := Apple; Dessert := My_PC; -- ERROR (caught at compile time)
17
ada-typesI- 17 Built-in enumeration types type Boolean is (False, True); type Character is (…. -- full ASCII. type Wide_Character is ( … -- Unicode, or ISO646
18
ada-typesI- 18 Array Types Index is typed: type weekday is (Mon, Tue, Wed, Thu, Fri); type workhours is array (Weekday) of integer; -- domain is Weekday, range is -- an int representing number of hours Predefined array: type String is array (Positive range <>) of Character;
19
ada-typesI- 19 Abstraction mechanisms Packages Private types Objects and Inheritance Classes, polymorphism, dynamic dispatching Generic units Concurrency : tasks and protected types
20
ada-typesI- 20 Object-oriented Programming Type extension Inheritance and overriding Run-time dispatching Polymorphism Class-wide programming Abstract types and subprograms
21
ada-typesI- 21 Inheritance Three goals: 1. Define one type in terms of another with extensions. (like java class inheritance) 2. Allow derived type (one with extensions) to redefine operations. 3. Be able to determine which operation to use at runtime.
22
ada-typesI- 22 Type Hierarchies called “class” in Ada A class is a family of types with the same ancestor (unlike C++/Java classes which are themselves hierarchically related) An object of the class is identified at run-time by its tag. Dynamic dispatching uses the tag of the object to determine the operation that applies. Dynamic = runtime. (This responds to third goal above.) A classwide operation applies uniformly to all member of the class. Reminder: Ada type is similar to Java class Ada class is similar to hierarchically related Java classes.
23
ada-typesI- 23 Type Extension Mechanism to define new types by enrichment (i.e. add fields): type GeoThing is tagged record X_Coord, Y_Coord : Integer; end record; type Circle is new GeoThing with record Radius : Float; end record;
24
ada-typesI- 24 Functions in type hierarchies function Distance(O: in GeoThing) return Float is begin return Sqrt(O.X_Coord ** 2 + O.Y_Coord**2); end record; function Area(O: in GeoThing) return Float is begin return 0.0; -- make it 0 because a GeoThing by default is a point end Area;
25
ada-typesI- 25 Functions in type hierarchies function Area(O: in Circle) return Float is begin return 3.14*C.Radius**2; -- circle has a different area from generic GeoThing end Area; -- So, distance function will apply to GeoThing and Circle but Area must be -- redefined for Circle. -- This implies that the function Area that is going to be called should depend - - on the type of the object.
26
ada-typesI- 26 Use of these functions O: GeoThing := (3.2, 2.1); -- a geothing at location 3.2, 2.1 C: Circle:= (1.0, 0.0, 4.2); -- a circle with center 1.0, 0.0 and radius 4.2 Area(O); -- returns 0.0 Area( C ); -- returns the area of the circle having radius 4.2 -- All of these facts can be determined at compile time. So this is called -- static binding.
27
ada-typesI- 27 Class-wide Functions In Ada, unlike Java and C++, a class is a hierarchy of types. (Types are analogous to classes in those languages). Suppose we want to define a function that applies to all types of a class and that does something different for different types in the class. In contrast: the function distance applies to all types of a class but does the same thing for the different types in the class.
28
ada-typesI- 28 Example of Class function function SquareArea(O: in GeoThing’Class) return Float is begin return (Area(O))**2; -- Call the area function for the object passed. end SquareArea; -- Unlike the distance function this one depends on the type -- Area function. Which version of Area to call is determined at runtime and -- the proper version is then “dispatched”. -- Please check out pp. 30-38 of Barnes (Point, Circle, Moment examples).
29
ada-typesI- 29 Implications of not using Class function SquareArea(O: in GeoThing) return Float is begin return (Area(O))**2; -- Call the area function for GeoThings always end SquareArea; -- Even if you called this one with a Circle, you’d call the Area function for -- GeoThings. This would be bad.
30
ada-typesI- 30 Advanced Considerations: overdoing inheritance It’s not always a good idea to use inheritance. Consider the following (Barnes chap 19): type Cylinder is new Circle with record Height: Float; -- cyliner is circle with height; sounds plausible… end Cylinder; -- To see whether it is good: ask can the class wide procedures apply to -- this new object (e.g. what is distance to a cylinder?). -- It just doesn’t make sense.
31
ada-typesI- 31 Advanced Considerations: has vs. isa A Cylinder isa Circle doesn’t seem right. How about a Cylinder has a Circle. type Cylinder is tagged record Base: Circle; Height: Float; end Cylinder; -- We express “has” by making a Circle a member of Cylinder. -- This way we don’t get spurious inheritance.
32
ada-typesI- 32 Generic Units (Barnes chapter 11) The basic tool for software reuse that cuts across types whether members of the same class or not. Parameters can be types, objects, subprograms, packages. Akin to C++ templates. Absent from Java so far.
33
ada-typesI- 33 A Generic Procedure (does not depend on nature of T) Generic type Item is private; procedure Exchange (X, Y : in out Item); procedure Exchange (X, Y : in out Item) is T: Item; begin T: = X; X := Y; Y := T; end;
34
ada-typesI- 34 Instantiating the Generic Procedure for other types procedure Swap is new Exchange(Float); procedure Swap is new Exchange(Integer); procedure Swap is new Exchange(Date); … -- So we can use Swap on many different types
35
ada-typesI- 35 A Generic Package (interface) Generic type T is private; package Stacks is type Stack is private; procedure Push (Thing : T ; On : in out Stack); … private type Arr is array (1.. Max) of T; type stack is record Top : Integer := 0; contents : Arr; end record; end Stacks; -- Body is pretty conventional (see section 11.1 of Barnes)
36
ada-typesI- 36 Use of Stack Package (Barnes 17.1) declare package mystack is new Stack(129, Float); -- stack package of a certain size and type -- mystack is now instantiated and can be used just as the Math_Functions -- package was used before. begin X: Float:= 3.2; mystack.push(X); …
37
ada-typesI- 37 Other Topics You Should Understand for project/core exam Abstract base classes (define interfaces to functions but no bodies, e.g. p. 38) Mixin Inheritance (mix generics and inheritance e.g. p. 466) Reflection (asking the type of an object). Tasking – we will discuss later Exceptions – we will discuss later
38
ada-typesI- 38 The Type Model Types and Subtypes Declarations and their scope Objects, constants and variables Scalar types Array types Record types Access types
39
ada-typesI- 39 Types and Subtypes A type is a set of values and a group of operations Types with different names are distinct and incompatible (part of strong typing): name equivalence everywhere, instead of structural equivalence. (As we saw, if colors and days of the week are represented by integers, don’t want to be able to assign Wednesday to a color.) Subtypes of the same base type are compatible.
40
ada-typesI- 40 Built-in subtypes type Integer is.. -- implementation defined subtype Positive is integer range 1.. Integer’Last; -- useful attribute subtype Natural is integer range 0.. Integer’Last; X : integer := 500; Y : Positive := 2 * X; Z : Natural := - Y; -- illegal, raises constraint error
41
ada-typesI- 41 Compile-time vs. run-time Type properties are enforced by the compiler whenever possible: x : integer := false; l-- program rejected x : positive := f (z); l-- if f returns a non-integer, then program rejected, else need to check value at run-time (in this sense dynamic)
42
ada-typesI- 42 Declarations and Scope Declarations are elaborated in order of appearance in the program. Entities become visible at the end of their declaration (usually) Block structure allows arbitrary nesting of declarative regions. Declarations can appear in lsubprograms lpackages lblocks l...
43
ada-typesI- 43 Blocks Declare X : Integer := F (5); Y : Integer := 2 * X; Z : Integer := Y * Z; -- Error: premature use of Z X : Float ; -- Error: duplicate begin declare X : Float := Float (Y); -- hides outer X begin Put_Line (Float’Image (X)); end;
44
ada-typesI- 44 Variables and Constants Variable declaration: Limit : Integer := 25; Offset : Integer range 1.. 20; Constant declaration: Sqrt2 : constant float := Sqrt (2.0); Always : constant Boolean := True; Never : constant Boolean := not Always;
45
ada-typesI- 45 Variables must be constrained Subtype is constrained: First_Name : String (1..5) := “Ralph”; but not necessarily static (i.e. could depend on runtime values): Last_Name : String (1.. X * 2); else subtype is indefinite but initial value provides bounds: Comment : String := “this is obvious”; -- bounds are 1.. 15
46
ada-typesI- 46 Multiple Declarations This, That : T := F (1, 2, 3); Is equivalent to This : T := F (1, 2, 3); That : T := F (1, 2, 3); F is called twice. Important if expression has side-effect: type Ptr is access R; P1, P2 : Ptr := new R; two R’s are allocated.
47
ada-typesI- 47 Number Declarations Pi : constant := 3.14159265; -- type deduced from value Half_Pi : constant := Pi / 2; -- mixed arithmetic OK Big : constant := 2 ** 200; -- legal One : constant := 2 * Big / (Big + Big); -- must be exact
48
ada-typesI- 48 Scalar Types Discrete types lInteger types lEnumeration Types Real types lFloating-point types lFixed_point types
49
ada-typesI- 49 Integer Types Several predefined types: Integer, Long_Integer, Short_Integer Specific bounds of type must be static: type My_Int is range -2 ** 16.. 2 ** 16 - 1; type Tiny is range 0.. 10; By giving explicit bounds, program is more portable: each compiler will figure out what hardware type corresponds (because integers can be 16 bits on some machines and 64 bits on others). Modular types: type Byte is mod 2 ** 8;
50
ada-typesI- 50 Integer Operations Comparison Operators: = /= >= Addition Operators: + - Unary operators + - Multiplying operators * / mod rem Highest precedence Operators: ** abs
51
ada-typesI- 51 Boolean Operations All attributes of discrete types Boolean binary operators : and or xor Boolean unary operators : not Short-circuit operations : and then or else Membership operations : in not in When in doubt, parenthesize!
52
ada-typesI- 52 Control Structures Conventional sequential constructs: If-Statement Loop Case statement Goto and labels More novel forms for task communication.
53
ada-typesI- 53 If-Statement If Done (X, Y) then Success; Close_Up; elsif Almost_Done (X) then -- the only keyword that isn’t English Hurry (Y); else if X = 0 then Call_For_Help (X) else Panic; end if; end if;
54
ada-typesI- 54 Loops Infinite loop: loop Put_Line (“Forever”); end loop; In general, better to stop: loop Put_Line (“Still_Going”); exit when Time_Is_Up; -- must be boolean value end loop;
55
ada-typesI- 55 Loops over discrete ranges for J in 1.. 1000 loop -- declares J for K in 1.. 0 loop -- empty range for Month in Feb.. Nov loop for Month in Months range Feb.. Nov loop for K in Positive loop -- might take a long time for Num in reverse 1.. 1000 loop -- descending order
56
ada-typesI- 56 While-Loops while abs (Result * Result - X ) > Epsilon loop Result := 0.5 * (X / Result + Result); end loop; Effect of Until can be obtained with while and exit statements.
57
ada-typesI- 57 Named Loops search : while X > 0 loop X := F(X, Y); refine: for J in 1.. N loop Y := G (Z); exit search when X = 0.0; end loop refine; if T > 20 then exit; end if; -- alternate form end loop search;.
58
ada-typesI- 58 Case Statements Most programs are interpreters for some abstract machine => case statement is most useful control structure! Works naturally with discrete types, in particular enumerations. Case alternatives must cover all values of the range
59
ada-typesI- 59 Case Statements X : Integer;.. Case (X+1) is -- Expression of integer type when Integer’First.. 0 => Handle_Non_Positive; when 2.. 4 | 6 | 8 => Process (X); when 9..12 | 2 => null; when others => Use_Default (X); -- Required Display (X); end case; can use qualification to restrict range: case Int’(x+1) is...
60
ada-typesI- 60 Goto Statement Occasionally useful. Syntax of maximum ugliness to discourage use: while Going loop Compute_Some; if Hopeless then goto next_try; end if; Compute_Some=More; > Adjust_Computation; end loop; Restricted range. Raise statement is wild jump.
61
ada-typesI- 61 Subprograms Functions and procedures. Functions only have in-parameters. Functions may return unconstrained types. Function execution must end in return statement Parameter passing by copy-return for scalar types. Parameter passing not specified for non-tagged types. Positional and named notation in calls. Defaults for in-parameters.
62
ada-typesI- 62 Functions function F (X : integer := 0; Y : Float := Pi; Maybe : Boolean := True) return Integer; … F (10, 0.0, False) F (5) -- equivalent to F (5, Pi, True) F (Maybe => False) -- equivalent to F(0, Pi, False)
63
ada-typesI- 63 Operators Like functions, but usable in infix notation. Package Bignums is type Bignum is private; Zero : constant Bignum; -- deferred constant function “+” (X, Y : Bignum) return Bignum; function “*” (X, Y : Bignum) return Bignum; function Image (X : Bignum) return String; private.. End Bignums; Must respect syntax: no defaults, no unary “*”, etc.
64
ada-typesI- 64 Attributes Attributes denote properties of a type, or type-specific properties of a value -Boolean’Size -- 1, because single bit -character’size -- 8 bits -month’pos (Jul) -- involves type and literal -table’length (1) -- specify array and dimension Could be written as a function, but functions don’t take types as arguments => so need new syntax.
65
ada-typesI- 65 Attributes on Discrete Types Byte’First, Long_Integer’Last -- applies to type or subtype Weekday’Succ (Today) -- like function call Integer’Succ (X*Y) -- like adding one Boolean’Pred (True) -- Yields False Boolean’Succ (True) -- Exception Weekday’Pos (Mon) -- Yields 0 Weekday’Val (3) -- Yields Thu Positive’Max (X, Y) -- function with two args
66
ada-typesI- 66 Real Types All computations are approximate: Fixed point type: absolute bound on error: type temp is delta 2 ** (-16) range -100.0.. 100.0; Floating point type: relative bound on error: type Angle is digits 7 range -2.0.. 2.0; Predefined floating point types: Float, Long_Float, etc.
67
ada-typesI- 67 Derived Types A general mechanism for creating new types with the properties of existing ones: type Like_T is new T; -- same set of values, same operations. type Small_Int is range 1.. 10; equivalent to type Anon is new Integer; subtype Small_Int is Anon range 1.. 10; and all arithmetic operations are inherited
68
ada-typesI- 68 Array Types Index types can be of any discrete type Component type must be definite: type class_list is array ( 1.. 100) of String (1..10); -- OK type class_list is array ( 1.. 100) of String; -- Error, which kind of string? Subtype constrains all indices or none: type Matrix is array (positive range <>, positive range <>) of Long_Float; -- positive matrix subtype Table is Matrix; subtype Rotation is Matrix (1.. 3, 1.. 3);
69
ada-typesI- 69 Anonymous Array Types Grades : array (1.. Num_Students) of Natural; Grades is a variable. type of Grades has no name: distinct from any other array types. Ar1, Ar2 : array (1.. 10) of Boolean; … Ar1 := Ar2; -- Error: different (anonymous) types. If type is useful, it deserves to have a name.
70
ada-typesI- 70 Array Attributes Array Attributes type Matrix is array (Positive range <>, Positive range <>) of Float; subtype Rect is Matrix (1.. 3, 1.. 5); M3 : Rect; M3’First (1) -- Yields 1 M3’First -- same. Rect’length (2) -- Yields 5 (applies to type) M3’range (2) -- equivalent to 1..5 String’Length -- ERROR: unconstrained
71
ada-typesI- 71 Array Aggregates Array Aggregates Expression that yields an array value: A := (1, 2, 3, 10); -- positional A := (1, others => 0); -- notation for default. A := (1..3 => 1, 4 => -999); -- component associations Default can only be used if bounds are known: A : String (1.. 10) := (others => ‘?’); -- OK A : String := (others => ‘?’); -- Error : unknown bounds.
72
ada-typesI- 72 Aggregates and Qualification Aggregates and Qualification Aggregate may be ambiguous: type Vector is array (1.. 3) of Float; procedure Display (V : vector); type Assay is array (1.. 3) of Float; procedure Display (A : assay); … Display ((1.0, 1.2, 1.5)); -- ambiguous Display (Vector ‘ (1.0, 1.2, 1.5)); -- OK.
73
ada-typesI- 73 Multidimensional Arrays Multidimensional Arrays Aggregates given in row-major order with subaggregates: type Square is array (1.. 3, 1.. 3) of Integer; Unit : constant Square := ( (1, 0,0), (0, 1, 0), (0, 0, 1)); Two-dimensional array is NOT array of arrays: type vector is array (1.. 3) of Integer; type V3 is array (1.. 3) of vector; -- not convertible to Square
74
ada-typesI- 74 Operations on One_Dimensional Arrays Boolean operations extend pointwise: type Set is array (1.. Card) of Boolean; S1, S2,S3 : Set; … S3 := S1 and S2; -- Intersection lexicographic comparisons on arrays of discrete types: S1 := (T, T, T); S2 := (T, T, F);.. S2 < S1 -- yields True
75
ada-typesI- 75 Concatenation and Slicing Both operations yield the base type: type Table is array (1..10) of Integer; T1, T2 : Table; … T1 & T2 -- What type? Declaration equivalent to: type Anon is array (integer range <>) of Integer; subtype Table is Anon (1.. 10); T1 & T2, T1 (X.. Y) are of type Anon
76
ada-typesI- 76 Specifying a range subtype Sub is Positive range 2.. 4; Label : String (1..10) := “transcends” ; … Label (2.. 4) -- Yields “ran” Label (Integer range 2.. 4) -- Same Label (Sub) -- Ditto Also used in loops and case statements.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.