Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Introduction to Ada Programming Languages Fall 2002.

Similar presentations


Presentation on theme: "An Introduction to Ada Programming Languages Fall 2002."— Presentation transcript:

1 An Introduction to Ada Programming Languages Fall 2002

2 Basic Structure of a Program A program is a collection of units A program is a collection of units Packages Packages Functions Functions Procedures Procedures Bound together to form a program Bound together to form a program Typically a unit is stored in a file Typically a unit is stored in a file Units reference other units Units reference other units

3 Procedure procedure H (M : Integer) is declarations begin statements return; end H; procedure H (M : Integer) is declarations begin statements return; end H; Typical use is procedure Main is … which defines the main program Typical use is procedure Main is … which defines the main program

4 Function function Max (A : Integer; B : Integer) return Integer is Result : Integer; begin if A > B then Result := A; else Result := B; end if; return Result; end Max; function Max (A : Integer; B : Integer) return Integer is Result : Integer; begin if A > B then Result := A; else Result := B; end if; return Result; end Max;

5 Packages Packages define a related collection of types, and subprograms (procedure and functions) Packages define a related collection of types, and subprograms (procedure and functions) A package provides a set of services to a client A package provides a set of services to a client A package may be a client of another package A package may be a client of another package

6 Package Spec (Declaration) package X is declarations types subprogram specs (but not subprogram bodies) end X; package X is declarations types subprogram specs (but not subprogram bodies) end X;

7 Subprogram Specs procedure Print_In_Hex (X : Integer); procedure Print_In_Hex (X : Integer); function Max (A, B : Integer) return Integer; function Max (A, B : Integer) return Integer; Note the semicolon instead of is Note the semicolon instead of is A subprogram spec has everything you need to know to use the subprogram A subprogram spec has everything you need to know to use the subprogram A client needs only the spec A client needs only the spec

8 Package Bodies package body X is declarations subprograms local to body variables/constants local to body subprogram bodies for subprogram specs appearing in the package spec begin initialization statements end X; package body X is declarations subprograms local to body variables/constants local to body subprogram bodies for subprogram specs appearing in the package spec begin initialization statements end X;

9 How to be A Client To access a package, use a WITH: with Calendar; procedure Main is Today : Calendar.Time; … end Main; To access a package, use a WITH: with Calendar; procedure Main is Today : Calendar.Time; … end Main;

10 The Use Clause Accessing Stuff in Calendar without dots Accessing Stuff in Calendar without dots with Calendar; use Calendar; procedure Main is Today : Time; … end Main; with Calendar; use Calendar; procedure Main is Today : Time; … end Main;

11 Package Bodies as Clients with Calendar; package body Julian_Calendar_Stuff is … end Julian_Calendar_Stuff; with Calendar; package body Julian_Calendar_Stuff is … end Julian_Calendar_Stuff; Here we have the implementation of a package done using stuff in another package Here we have the implementation of a package done using stuff in another package

12 Package Specs as Clients A package spec can build on another spec A package spec can build on another spec with Calendar; use Calendar package To_Do_List is … procedure Enter (T : Time; M : String); -- Enter new item in todo list. Time is -- deadline. M is description. end To_Do_List; with Calendar; use Calendar package To_Do_List is … procedure Enter (T : Time; M : String); -- Enter new item in todo list. Time is -- deadline. M is description. end To_Do_List;

13 The Idea of a Package Spec Write the package spec Write the package spec It is like a contract between client and body of the spec It is like a contract between client and body of the spec Write the body Write the body Write the client Write the client Last two activities are completely independent (and should not talk to one another except “via” the spec) Last two activities are completely independent (and should not talk to one another except “via” the spec)

14 Integer Type Declarations Type Integer is built in Type Integer is built in But you don’t want to use it But you don’t want to use it Because its range is implementation defined Because its range is implementation defined Because it is defined to match the machine not your problem Because it is defined to match the machine not your problem Because it does not take advantage of strong typing to prevent errors Because it does not take advantage of strong typing to prevent errors

15 Defining Integer Types Define type according to use Define type according to use type Day_In_Year is range 1.. 366; type Age is range 0.. 130; type Temperature is range -20.. +180; type Day_In_Year is range 1.. 366; type Age is range 0.. 130; type Temperature is range -20.. +180; Now we can define variables of the type Now we can define variables of the type Today_Day : Day_In_Year; Employee_Age : Age; Machine_Room_Temp : Temperature; Today_Day : Day_In_Year; Employee_Age : Age; Machine_Room_Temp : Temperature;

16 Why Define Integer Types No dependence on implementation No dependence on implementation Unlike type int in C Unlike type int in C Range of types matches problem Range of types matches problem Get an error or warning at compile time Get an error or warning at compile time Age := 200; Age := 200; Or an exception at runtime Or an exception at runtime Age := Age + 1000; Age := Age + 1000;

17 Strong Typing Cannot mix integer types: Cannot mix integer types: Current_Temp : Temperature; Current_Pressure : Pressure; Current_Temp : Temperature; Current_Pressure : Pressure; Current_Temp := Current_Pressure + 1; Current_Temp := Current_Pressure + 1; Error, cannot assign pressure to temperature Error, cannot assign pressure to temperature Current_Temp := Current_Temp + Current_Pressure Current_Temp := Current_Temp + Current_Pressure Error, cannot add temperature to pressure Error, cannot add temperature to pressure

18 Integer Subtypes A subtype creates a limited range A subtype creates a limited range But is still the same type But is still the same type subtype OK_Operating_Range is Temperature range 70.. 80; Room_Temp : Temperature; Machine_Room_Temp : OK_Operating_Range … Machine_Room_Temp := Room_Temp; subtype OK_Operating_Range is Temperature range 70.. 80; Room_Temp : Temperature; Machine_Room_Temp : OK_Operating_Range … Machine_Room_Temp := Room_Temp; Raises exception if Room_Temp out of range Raises exception if Room_Temp out of range

19 Catching Exceptions You can catch an exception at run time You can catch an exception at run time begin … Machine_Room_Temp := Room_Temp … exception when Constraint_Error => recovery stuff end; begin … Machine_Room_Temp := Room_Temp … exception when Constraint_Error => recovery stuff end;

20 Unsigned (Modular) Types Modular types have wrap around: Modular types have wrap around: type M is mod 7; -- values are 0,1,2,3,4,5,6 q : m := 6; -- initialization … q := q + 2; -- result is 1 type M is mod 7; -- values are 0,1,2,3,4,5,6 q : m := 6; -- initialization … q := q + 2; -- result is 1 Most common use, conventional unsigned Most common use, conventional unsigned type Uns_32 is mod 2 ** 32; type Uns_32 is mod 2 ** 32; Remember that twos complement arithmetic is equivalent to arithmetic mod 2**wordsize Remember that twos complement arithmetic is equivalent to arithmetic mod 2**wordsize

21 Real Types Float types (control relative accuracy) Float types (control relative accuracy) type My_Float is digits 7; type Xfloat is digits 7 range 1.0.. 10.0; subtype F1 is My_Float range 1.0.. 5.0; type My_Float is digits 7; type Xfloat is digits 7 range 1.0.. 10.0; subtype F1 is My_Float range 1.0.. 5.0; Digits is decimal digits of relative precision Digits is decimal digits of relative precision There is a formal model for fpt in Ada There is a formal model for fpt in Ada Target independent (parametrized) Target independent (parametrized) Guarantees minimal accuracy Guarantees minimal accuracy Operations defined in terms of model numbers Operations defined in terms of model numbers Results fall in defined model interval Results fall in defined model interval

22 Fixed-Point Types Fixed-point types are real types where you control the absolute accuracy. Fixed-point types are real types where you control the absolute accuracy. Typically implemented as scaled integers Typically implemented as scaled integers type Velocity is delta 0.125 range 0.0.. 10.0; type Velocity is delta 0.125 range 0.0.. 10.0; Decimal fixed-point types Decimal fixed-point types Decimal small Decimal small Typical use in financial programming Typical use in financial programming type Money is digits 10 delta 0.01 range 0.00.. 999_999_999.00; type Money is digits 10 delta 0.01 range 0.00.. 999_999_999.00;

23 Character Types Built in types Built in types Character (8-bit Latin-1) Character (8-bit Latin-1) Wide_Character (16-bit Unicode/ISO 10646) Wide_Character (16-bit Unicode/ISO 10646) Good enough for most purposes, but you can define your own types: Good enough for most purposes, but you can define your own types: type My_Character is (‘A’, ‘B’, ‘C’, ….); type My_Character is (‘A’, ‘B’, ‘C’, ….); Note on standard types Note on standard types Standard types are in package Standard that is automatically visible in every unit. Standard types are in package Standard that is automatically visible in every unit.

24 Enumeration Types An enumeration type is a sequence of ordered enumeration literals: An enumeration type is a sequence of ordered enumeration literals: type State is (Off, Powering_Up, On); type State is (Off, Powering_Up, On); No arithmetic defined No arithmetic defined S1, S2 : State; S1 := S1 + S2; -- Illegal S1, S2 : State; S1 := S1 + S2; -- Illegal Can add/subtract one Can add/subtract one State’Pred (S1) State’Succ (S2) State’Pred (S1) State’Succ (S2) These are examples of attributes These are examples of attributes

25 Boolean Types Predefined enumeration type Predefined enumeration type type Boolean is (False, True); type Boolean is (False, True); Expressions of type boolean used in Expressions of type boolean used in if statements if statements while loops while loops exit statements exit statements Etc. Etc.

26 Access Types Access types function like pointers Access types function like pointers But are not necessarily implemented that way But are not necessarily implemented that way type r is access integer; type s is access all integer; type r is access integer; type s is access all integer; The all allows the access value to reference any item at all. Without all, you can only reference objects specifically allocated for the pool in question. The all allows the access value to reference any item at all. Without all, you can only reference objects specifically allocated for the pool in question.

27 Using Access Types Allocate an object using new Allocate an object using new type AI is access all integer; Ptr : AI; … Ptr := new Integer; -- uninitialized Ptr := new Integer’(12); -- initialized type AI is access all integer; Ptr : AI; … Ptr := new Integer; -- uninitialized Ptr := new Integer’(12); -- initialized To obtain value dereference: To obtain value dereference: V : Integer; … V := Ptr.all; V : Integer; … V := Ptr.all;

28 Array Types Arrays can have 1 or more subscripts Arrays can have 1 or more subscripts type Vector is type Vector is array (Integer range 1.. 10) of Integer; type Matrix is array (Integer range 0.. 10, Character range ‘A’.. ‘Z’) of Vector; array (Integer range 1.. 10) of Integer; type Matrix is array (Integer range 0.. 10, Character range ‘A’.. ‘Z’) of Vector; VV : Vector := (others => 10); -- aggregate MM : Matrix; … MM (5, ‘C’) := VV; VV (1.. 5) := VV (2.. 6); -- slicing (one dim only)

29 Array Bounds and Types Are the bounds of an array answer part of the properties of the array type? Are the bounds of an array answer part of the properties of the array type? Things are much cleaner if we answer yes, as in Pascal, but this is very limiting Things are much cleaner if we answer yes, as in Pascal, but this is very limiting For example, a sort routine cannot take a vector of any size to sort. For example, a sort routine cannot take a vector of any size to sort. Instead we consider the bounds to be like the range of an integer type Instead we consider the bounds to be like the range of an integer type

30 Unconstrained Arrays Unconstrained array type has no bounds Unconstrained array type has no bounds type UA is array (Int range <>) of Int; -- cannot use UA to declare a variable -- instead must build a subtype subtype UA5 is UA (1.. 5); UAV5 : UA5 := (6,5,4,3,2); -- can also set bounds for a variable UAV2 : UA (1.. 2); type UA is array (Int range <>) of Int; -- cannot use UA to declare a variable -- instead must build a subtype subtype UA5 is UA (1.. 5); UAV5 : UA5 := (6,5,4,3,2); -- can also set bounds for a variable UAV2 : UA (1.. 2);

31 String Types A string type is an array whose elements are a character type. A string type is an array whose elements are a character type. Two standard built in string types Two standard built in string types type String is array (Natural range <>) of Character; type Wide_String is array (Natural range <>) of Wide_Character; S : String (1.. 5) := “Hello”; type String is array (Natural range <>) of Character; type Wide_String is array (Natural range <>) of Wide_Character; S : String (1.. 5) := “Hello”; Note: Natural is a predefined subtype of Integer with bounds 0.. Integer’Last; Note: Natural is a predefined subtype of Integer with bounds 0.. Integer’Last;

32 Record Types Like struct in C Like struct in C type Date is record Year : Year_Number := 2002; -- default Month : Month_Number; Day : Day_Number; end record; DD : Date; EE : Date := (2001, 8, Day => 27); … DD.Month := EE.Month – 1; type Date is record Year : Year_Number := 2002; -- default Month : Month_Number; Day : Day_Number; end record; DD : Date; EE : Date := (2001, 8, Day => 27); … DD.Month := EE.Month – 1;

33 Arrays/Records and Access Types Access types and records/arrays Access types and records/arrays type A is array (Int range 0.. 10) of Int; type AP is access A; AV : AP; … AV.all (3) := AV (4); -- can omit.all here type A is array (Int range 0.. 10) of Int; type AP is access A; AV : AP; … AV.all (3) := AV (4); -- can omit.all here Similarly do not need.all for fields of records Similarly do not need.all for fields of records DP.Month := DP.all.Month + 1; DP.Month := DP.all.Month + 1;

34 What about Union Types? The union type in C is fundamentally unsafe, and therefore unacceptable The union type in C is fundamentally unsafe, and therefore unacceptable union (int, float) puzzle; union (int, float) puzzle; Now puzzle has either an int or a float Now puzzle has either an int or a float But at runtime, cannot tell which But at runtime, cannot tell which So we have to trust the programer So we have to trust the programer In Ada we are short on trust In Ada we are short on trust

35 Instead, Discriminated Types A record can have discriminants: A record can have discriminants: type IF is (Int, Float); type Int_Float (V : IF := Int) is record case V is when Int => Int_Val : Integer; when Float => Float_Val : Float; end case; end record; type IF is (Int, Float); type Int_Float (V : IF := Int) is record case V is when Int => Int_Val : Integer; when Float => Float_Val : Float; end case; end record; Now the value of the discriminant V shows what type is currently present Now the value of the discriminant V shows what type is currently present

36 More on Discriminated Records Referencing a discriminanted type Referencing a discriminanted type Puzzle : Int_Float; … Puzzle := (Float, 1.0); F := Puzzle.Float_Val; -- OK I := Puzzle.Int_Val; -- raise exception … Puzzle.V := Int; -- not allowed! Puzzle : Int_Float; … Puzzle := (Float, 1.0); F := Puzzle.Float_Val; -- OK I := Puzzle.Int_Val; -- raise exception … Puzzle.V := Int; -- not allowed!

37 More on Discriminated Records Can make subtypes Can make subtypes subtype PuzzleI is puzzle (Int); -- this type only holds int values subtype PuzzleI is puzzle (Int); -- this type only holds int values Can dimension arrays from discriminant: Can dimension arrays from discriminant: Subtype Vlen is Integer range 1.. 10; type Vstr (Vlen : Integer := 0) is record Data : String (1.. Vlen); end record; VV : Vstr := (5, “hello”); Subtype Vlen is Integer range 1.. 10; type Vstr (Vlen : Integer := 0) is record Data : String (1.. Vlen); end record; VV : Vstr := (5, “hello”);

38 Other Types Derived types (copying a type) Derived types (copying a type) Extended types (object oriented stuff) Extended types (object oriented stuff) Task types (active threads) Task types (active threads) Protected types (passive synchronization) Protected types (passive synchronization) More on all these later! More on all these later!

39 Statement Forms Assignment statement (is not an expression) Assignment statement (is not an expression) Variable := expression; Variable := expression; If statements If statements if condition then statements elsif condition then statements … else statements end if; if condition then statements elsif condition then statements … else statements end if;

40 Statement Forms (cont) Loops Loops for J in Integer range 1.. 10 loop statements end loop; for J in Integer range 1.. 10 loop statements end loop; while condition loop statements end loop; while condition loop statements end loop; loop statements end loop; loop statements end loop;

41 Statements (cont) Exit statement Exit statement exit; exit when condition; exit; exit when condition; Can only be used in a loop Can only be used in a loop Can use labels: Can use labels: Outer : loop Inner : loop … exit Inner when Done; end loop Inner; end loop Outer; Outer : loop Inner : loop … exit Inner when Done; end loop Inner; end loop Outer;

42 Statements (cont) Case statements Case statements case expression is when 0 => statements when 1 | 10 => statements when 2.. 9 => statements end case; case expression is when 0 => statements when 1 | 10 => statements when 2.. 9 => statements end case; All values in when branches must be static All values in when branches must be static All possible values of expression must be included exactly once All possible values of expression must be included exactly once Can use when others => to cover rest Can use when others => to cover rest

43 Statements (cont) Return statement Return statement return;-- procedure return expression;-- function return;-- procedure return expression;-- function Only in procedure/function Only in procedure/function Function must have at least one return Function must have at least one return Raise statement Raise statement raise exception-name; raise exception-name;

44 Declaring and Handling Exceptions Declaring an exception Declaring an exception Error, Disaster : exception; Error, Disaster : exception; Raising an exception Raising an exception raise Disaster; -- strips stack frames till a handler is found raise Disaster; -- strips stack frames till a handler is found Handling an exception Handling an exception exception when Disaster => statements exception when Disaster => statements

45 More on Exception Handling Anywhere we have begin end, we can do: Anywhere we have begin end, we can do: begin statements exception when handler => statements; when handler => statements; end; begin statements exception when handler => statements; when handler => statements; end;

46 Block Statement Block statement can be used anywhere Block statement can be used anywhere declare -- declare section optional declarations begin statements exception -- exception section optional handlers end; declare -- declare section optional declarations begin statements exception -- exception section optional handlers end;

47 Summary That’s enough to get you on your way! That’s enough to get you on your way! First assignment will be to do one of the ACM programming competition problems First assignment will be to do one of the ACM programming competition problems You do the program and make test data You do the program and make test data Your choice of examples Your choice of examples See website for URL See website for URL


Download ppt "An Introduction to Ada Programming Languages Fall 2002."

Similar presentations


Ads by Google