an introduction to ada programming languages fall 2002

47
An Introduction to An Introduction to Ada Ada Programming Languages Programming Languages Fall 2002 Fall 2002

Upload: margaret-ross

Post on 17-Dec-2015

222 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: An Introduction to Ada Programming Languages Fall 2002

An Introduction to AdaAn Introduction to Ada

Programming LanguagesProgramming Languages

Fall 2002Fall 2002

Page 2: An Introduction to Ada Programming Languages Fall 2002

Basic Structure of a ProgramBasic Structure of a Program

A program is a collection of unitsA program is a collection of unitsPackagesPackagesFunctionsFunctionsProceduresProcedures

Bound together to form a programBound together to form a programTypically a unit is stored in a fileTypically a unit is stored in a fileUnits reference other unitsUnits reference other units

Page 3: An Introduction to Ada Programming Languages Fall 2002

ProcedureProcedure

procedureprocedure H (M : Integer) H (M : Integer) isis declarationsdeclarationsbeginbegin statementsstatements returnreturn;;endend H; H;

Typical use is procedure Main is …Typical use is procedure Main is …which defines the main program which defines the main program

Page 4: An Introduction to Ada Programming Languages Fall 2002

FunctionFunction

functionfunction Max (A : Integer; B : Integer) Max (A : Integer; B : Integer) returnreturn Integer Integerisis Result : Integer; Result : Integer;beginbegin ifif A > B A > B thenthen Result := A; Result := A; elseelse Result := B; Result := B; end ifend if;; returnreturn Result; Result;endend Max; Max;

Page 5: An Introduction to Ada Programming Languages Fall 2002

PackagesPackages

Packages define a related collection Packages define a related collection of types, and subprograms of types, and subprograms (procedure and functions)(procedure and functions)

A package provides a set of services A package provides a set of services to a clientto a client

A package may be a client of another A package may be a client of another packagepackage

Page 6: An Introduction to Ada Programming Languages Fall 2002

Package Spec (Declaration)Package Spec (Declaration)

packagepackage X X isis declarationsdeclarations types types subprogram specs subprogram specs (but not subprogram bodies) (but not subprogram bodies)endend X; X;

Page 7: An Introduction to Ada Programming Languages Fall 2002

Subprogram SpecsSubprogram Specs

procedureprocedure Print_In_Hex (X : Integer); Print_In_Hex (X : Integer);functionfunction Max (A, B : Integer) Max (A, B : Integer)

returnreturn Integer; Integer;Note the semicolon instead of Note the semicolon instead of isisA subprogram spec has everything you A subprogram spec has everything you

need to know to use the subprogramneed to know to use the subprogramA client needs only the specA client needs only the spec

Page 8: An Introduction to Ada Programming Languages Fall 2002

Package BodiesPackage Bodies

packagepackage bodybody X X isis declarationsdeclarations subprograms local to body subprograms local to body variables/constants local to body variables/constants local to body subprogram bodies for subprogram subprogram bodies for subprogram specs appearing in the package spec specs appearing in the package specbeginbegin initialization statementsinitialization statementsendend X; X;

Page 9: An Introduction to Ada Programming Languages Fall 2002

How to be A ClientHow to be A Client

To access a package, use a WITH:To access a package, use a WITH:

withwith Calendar; Calendar;procedureprocedure Main Main isis Today : Calendar.Time; Today : Calendar.Time;…… endend Main; Main;

Page 10: An Introduction to Ada Programming Languages Fall 2002

The Use ClauseThe Use Clause

Accessing Stuff in Calendar without Accessing Stuff in Calendar without dotsdots

withwith Calendar; Calendar;useuse Calendar; Calendar;procedureprocedure Main Main isis Today : Time; Today : Time;…… endend Main; Main;

Page 11: An Introduction to Ada Programming Languages Fall 2002

Package Bodies as ClientsPackage Bodies as Clients

withwith Calendar; Calendar;package package bodybody Julian_Calendar_Stuff Julian_Calendar_Stuff isis … …endend Julian_Calendar_Stuff; Julian_Calendar_Stuff;

Here we have the implementation of Here we have the implementation of a package done using stuff in a package done using stuff in another packageanother package

Page 12: An Introduction to Ada Programming Languages Fall 2002

Package Specs as ClientsPackage Specs as Clients

A package spec can build on another A package spec can build on another specspec

withwith Calendar; Calendar;useuse Calendar Calendarpackagepackage To_Do_List To_Do_List isis … … procedureprocedure Enter (T : Time; M : Enter (T : Time; M : String);String); -- Enter new item in todo list. Time is -- Enter new item in todo list. Time is -- deadline. M is description. -- deadline. M is description.endend To_Do_List; To_Do_List;

Page 13: An Introduction to Ada Programming Languages Fall 2002

The Idea of a Package SpecThe Idea of a Package Spec

Write the package specWrite the package spec It is like a contract between client It is like a contract between client

and body of the specand body of the specWrite the bodyWrite the bodyWrite the clientWrite the clientLast two activities are completely Last two activities are completely

independent (and should not talk to independent (and should not talk to one another except “via” the spec)one another except “via” the spec)

Page 14: An Introduction to Ada Programming Languages Fall 2002

Integer Type DeclarationsInteger Type Declarations

Type Integer is built inType Integer is built inBut you don’t want to use itBut you don’t want to use it

Because its range is implementation Because its range is implementation defineddefined

Because it is defined to match the Because it is defined to match the machine not your problemmachine not your problem

Because it does not take advantage of Because it does not take advantage of strong typing to prevent errorsstrong typing to prevent errors

Page 15: An Introduction to Ada Programming Languages Fall 2002

Defining Integer TypesDefining Integer Types

Define type according to useDefine type according to usetypetype Day_In_Year Day_In_Year is rangeis range 1 .. 366; 1 .. 366;

typetype Age Age is rangeis range 0 .. 130; 0 .. 130;typetype Temperature Temperature is rangeis range -20 .. -20 .. +180;+180;

Now we can define variables of the typeNow we can define variables of the typeToday_Day : Day_In_Year;Today_Day : Day_In_Year;

Employee_Age : Age;Employee_Age : Age;Machine_Room_Temp : Temperature;Machine_Room_Temp : Temperature;

Page 16: An Introduction to Ada Programming Languages Fall 2002

Why Define Integer TypesWhy Define Integer Types

No dependence on implementationNo dependence on implementationUnlike type int in CUnlike type int in C

Range of types matches problemRange of types matches problemGet an error or warning at compile timeGet an error or warning at compile time

Age := 200;Age := 200;Or an exception at runtimeOr an exception at runtime

Age := Age + 1000;Age := Age + 1000;

Page 17: An Introduction to Ada Programming Languages Fall 2002

Strong TypingStrong Typing

Cannot mix integer types:Cannot mix integer types:Current_Temp : Temperature;Current_Temp : Temperature;

Current_Pressure : Pressure;Current_Pressure : Pressure;Current_Temp := Current_Pressure + 1;Current_Temp := Current_Pressure + 1;

Error, cannot assign pressure to Error, cannot assign pressure to temperaturetemperature

Current_Temp :=Current_Temp := Current_Temp + Current_Pressure Current_Temp + Current_PressureError, cannot add temperature to pressureError, cannot add temperature to pressure

Page 18: An Introduction to Ada Programming Languages Fall 2002

Integer SubtypesInteger Subtypes

A subtype creates a limited rangeA subtype creates a limited rangeBut is still the same typeBut is still the same type

subtypesubtype OK_Operating_Range OK_Operating_Range isis Temperature Temperature rangerange 70 .. 80; 70 .. 80;Room_Temp : Temperature;Room_Temp : Temperature;Machine_Room_Temp : Machine_Room_Temp : OK_Operating_RangeOK_Operating_Range……Machine_Room_Temp := Room_Temp;Machine_Room_Temp := Room_Temp;Raises exception if Room_Temp out of rangeRaises exception if Room_Temp out of range

Page 19: An Introduction to Ada Programming Languages Fall 2002

Catching ExceptionsCatching Exceptions

You can catch an exception at run You can catch an exception at run timetimebeginbegin

… … Machine_Room_Temp := Room_Temp Machine_Room_Temp := Room_Temp

… …exceptionexception whenwhen Constraint_Error => Constraint_Error => recovery stuffrecovery stuffendend;;

Page 20: An Introduction to Ada Programming Languages Fall 2002

Unsigned (Modular) TypesUnsigned (Modular) Types

Modular types have wrap around:Modular types have wrap around:typetype M M is modis mod 7; -- values are 0,1,2,3,4,5,6 7; -- values are 0,1,2,3,4,5,6

q : m := 6; -- initializationq : m := 6; -- initialization……q := q + 2; -- result is 1q := q + 2; -- result is 1

Most common use, conventional Most common use, conventional unsignedunsignedtypetype Uns_32 Uns_32 is modis mod 2 ** 32; 2 ** 32;

Remember that twos complement arithmetic is Remember that twos complement arithmetic is equivalent to arithmetic mod 2**wordsizeequivalent to arithmetic mod 2**wordsize

Page 21: An Introduction to Ada Programming Languages Fall 2002

Real TypesReal Types

Float types (control relative accuracy)Float types (control relative accuracy) typetype My_Float My_Float isis digitsdigits 7; 7;

typetype Xfloat Xfloat isis digits 7 digits 7 rangerange 1.0 .. 10.0; 1.0 .. 10.0;subtypesubtype F1 F1 isis My_Float My_Float rangerange 1.0 .. 5.0; 1.0 .. 5.0;

Digits is decimal digits of relative precisionDigits is decimal digits of relative precision There is a formal model for fpt in AdaThere is a formal model for fpt in Ada

Target independent (parametrized)Target independent (parametrized) Guarantees minimal accuracyGuarantees minimal accuracy Operations defined in terms of model numbersOperations defined in terms of model numbers Results fall in defined model intervalResults fall in defined model interval

Page 22: An Introduction to Ada Programming Languages Fall 2002

Fixed-Point TypesFixed-Point Types

Fixed-point types are real types where you Fixed-point types are real types where you control the absolute accuracy.control the absolute accuracy. Typically implemented as scaled integersTypically implemented as scaled integers typetype Velocity is Velocity is deltadelta 0.125 0.125 rangerange 0.0 .. 10.0; 0.0 .. 10.0;

Decimal fixed-point typesDecimal fixed-point types Decimal smallDecimal small Typical use in financial programmingTypical use in financial programming typetype Money is Money is digitsdigits 10 10

deltadelta 0.01 0.01 rangerange 0.00 .. 999_999_999.00; 0.00 .. 999_999_999.00;

Page 23: An Introduction to Ada Programming Languages Fall 2002

Character TypesCharacter Types

Built in typesBuilt in typesCharacter (8-bit Latin-1)Character (8-bit Latin-1)Wide_Character (16-bit Unicode/ISO Wide_Character (16-bit Unicode/ISO

10646)10646)Good enough for most purposes, but Good enough for most purposes, but

you can define your own types:you can define your own types:typetype My_Character My_Character isis (‘A’, ‘B’, ‘C’, ….); (‘A’, ‘B’, ‘C’, ….);

Note on standard typesNote on standard typesStandard types are in package Standard Standard types are in package Standard

that is automatically visible in every unit.that is automatically visible in every unit.

Page 24: An Introduction to Ada Programming Languages Fall 2002

Enumeration TypesEnumeration Types

An enumeration type is a sequence An enumeration type is a sequence of ordered enumeration literals:of ordered enumeration literals:typetype State State isis (Off, Powering_Up, On); (Off, Powering_Up, On);No arithmetic definedNo arithmetic defined

S1, S2 : State;S1, S2 : State;S1 := S1 + S2; -- IllegalS1 := S1 + S2; -- Illegal

Can add/subtract oneCan add/subtract oneState’Pred (S1)State’Pred (S1)

State’Succ (S2)State’Succ (S2)These are examples of attributesThese are examples of attributes

Page 25: An Introduction to Ada Programming Languages Fall 2002

Boolean TypesBoolean Types

Predefined enumeration typePredefined enumeration typetypetype Boolean Boolean isis (False, True); (False, True);

Expressions of type boolean used inExpressions of type boolean used inifif statements statementswhilewhile loops loopsexitexit statements statementsEtc.Etc.

Page 26: An Introduction to Ada Programming Languages Fall 2002

Access TypesAccess Types

Access types function like pointersAccess types function like pointersBut are not necessarily implemented But are not necessarily implemented

that waythat waytypetype r r is accessis access integer; integer;

typetype s s is access allis access all integer; integer;The The allall allows the access value to allows the access value to

reference any item at all. Without reference any item at all. Without allall, , you can only reference objects you can only reference objects specifically allocated for the pool in specifically allocated for the pool in question.question.

Page 27: An Introduction to Ada Programming Languages Fall 2002

Using Access TypesUsing Access Types

Allocate an object using Allocate an object using newnewtype type AI AI is access allis access all integer; integer;

Ptr : AI;Ptr : AI;……Ptr := Ptr := newnew Integer; Integer; -- uninitialized-- uninitializedPtr := Ptr := newnew Integer’(12); Integer’(12); -- initialized-- initialized

To obtain value dereference:To obtain value dereference:V : Integer;V : Integer;

……V := Ptr.V := Ptr.allall; ;

Page 28: An Introduction to Ada Programming Languages Fall 2002

Array TypesArray Types

Arrays can have 1 or more subscriptsArrays can have 1 or more subscripts typetype Vector Vector isis

arrayarray (Integer (Integer rangerange 1 .. 10) 1 .. 10) ofof Integer; Integer;typetype Matrix Matrix isis arrayarray (Integer (Integer rangerange 0 .. 10, 0 .. 10, Character Character rangerange ‘A’ .. ‘Z’) ‘A’ .. ‘Z’) ofof Vector; Vector;

VV : Vector := (others => 10); -- aggregateVV : Vector := (others => 10); -- aggregateMM : Matrix;MM : Matrix;……MM (5, ‘C’) := VV;MM (5, ‘C’) := VV;VV (1 .. 5) := VV (2 .. 6); -- slicing (one dim only)VV (1 .. 5) := VV (2 .. 6); -- slicing (one dim only)

Page 29: An Introduction to Ada Programming Languages Fall 2002

Array Bounds and TypesArray Bounds and Types

Are the bounds of an array answer part Are the bounds of an array answer part of the properties of the array type?of the properties of the array type?

Things are much cleaner if we answer Things are much cleaner if we answer yes, as in Pascal, but this is very limitingyes, as in Pascal, but this is very limiting

For example, a sort routine cannot take For example, a sort routine cannot take a vector of any size to sort.a vector of any size to sort.

Instead we consider the bounds to be Instead we consider the bounds to be like the range of an integer typelike the range of an integer type

Page 30: An Introduction to Ada Programming Languages Fall 2002

Unconstrained ArraysUnconstrained Arrays

Unconstrained array type has no Unconstrained array type has no boundsboundstypetype UA UA is arrayis array (Int range <>) (Int range <>) ofof Int; Int;

-- cannot use UA to declare a variable-- cannot use UA to declare a variable-- instead must build a subtype-- instead must build a subtypesubtypesubtype UA5 UA5 isis UA (1 .. 5); UA (1 .. 5);UAV5 : UA5 := (6,5,4,3,2);UAV5 : UA5 := (6,5,4,3,2);-- can also set bounds for a variable-- can also set bounds for a variableUAV2 : UA (1 .. 2);UAV2 : UA (1 .. 2);

Page 31: An Introduction to Ada Programming Languages Fall 2002

String TypesString Types

A string type is an array whose A string type is an array whose elements are a character type.elements are a character type.

Two standard built in string typesTwo standard built in string typestypetype String String is arrayis array

(Natural (Natural rangerange <>) of <>) of CharacterCharacter;;typetype Wide_String Wide_String is arrayis array (Natural (Natural rangerange <>) of <>) of Wide_CharacterWide_Character;;S : String (1 .. 5) := “Hello”;S : String (1 .. 5) := “Hello”;

Note: Natural is a predefined subtype of Note: Natural is a predefined subtype of Integer with bounds 0 .. Integer’Last;Integer with bounds 0 .. Integer’Last;

Page 32: An Introduction to Ada Programming Languages Fall 2002

Record TypesRecord Types

Like struct in CLike struct in Ctypetype Date Date isis recordrecord

Year : Year_Number := 2002; -- default Year : Year_Number := 2002; -- default Month : Month_Number; Month : Month_Number; Day : Day_Number; Day : Day_Number;end recordend record;;DD : Date;DD : Date;EE : Date := (2001, 8, Day => 27);EE : Date := (2001, 8, Day => 27);……DD.Month := EE.Month – 1;DD.Month := EE.Month – 1;

Page 33: An Introduction to Ada Programming Languages Fall 2002

Arrays/Records and Access Arrays/Records and Access TypesTypes

Access types and records/arraysAccess types and records/arraystypetype A A is arrayis array (Int (Int rangerange 0 .. 10) 0 .. 10) ofof

Int;Int;typetype AP AP is accessis access A; A;AV : AP;AV : AP;……AV.AV.allall (3) := AV (4); -- can omit . (3) := AV (4); -- can omit .allall here here

Similarly do not need .Similarly do not need .allall for fields of for fields of recordsrecords

DP.Month := DP.DP.Month := DP.allall.Month + 1;.Month + 1;

Page 34: An Introduction to Ada Programming Languages Fall 2002

What about Union Types?What about Union Types?

The union type in C is fundamentally The union type in C is fundamentally unsafe, and therefore unacceptableunsafe, and therefore unacceptableunionunion ( (intint, , floatfloat) puzzle;) puzzle;Now puzzle has either an Now puzzle has either an intint or a or a floatfloatBut at runtime, cannot tell whichBut at runtime, cannot tell whichSo we have to trust the programerSo we have to trust the programerIn Ada we are short on trust In Ada we are short on trust

Page 35: An Introduction to Ada Programming Languages Fall 2002

Instead, Discriminated TypesInstead, Discriminated Types

A record can have discriminants:A record can have discriminants:typetype IF IF isis (Int, Float); (Int, Float);

typetype Int_Float (V : IF := Int) Int_Float (V : IF := Int) is recordis record casecase V V isis whenwhen Int => Int_Val : Integer; Int => Int_Val : Integer; whenwhen Float => Float_Val : Float; Float => Float_Val : Float; end caseend case;;end recordend record;;

Now the value of the discriminant V Now the value of the discriminant V shows what type is currently presentshows what type is currently present

Page 36: An Introduction to Ada Programming Languages Fall 2002

More on Discriminated More on Discriminated RecordsRecords

Referencing a discriminanted typeReferencing a discriminanted typePuzzle : Int_Float;Puzzle : Int_Float;

……Puzzle := (Float, 1.0);Puzzle := (Float, 1.0);F := Puzzle.Float_Val; F := Puzzle.Float_Val; -- OK-- OKI := Puzzle.Int_Val; I := Puzzle.Int_Val; -- raise exception-- raise exception……Puzzle.V := Int; Puzzle.V := Int; -- not allowed! -- not allowed!

Page 37: An Introduction to Ada Programming Languages Fall 2002

More on Discriminated More on Discriminated RecordsRecords

Can make subtypesCan make subtypessubtypesubtype PuzzleI PuzzleI isis puzzle (Int); puzzle (Int);

-- this type only holds int values-- this type only holds int valuesCan dimension arrays from Can dimension arrays from

discriminant:discriminant:Subtype Vlen is Integer range 1 .. 10;Subtype Vlen is Integer range 1 .. 10;

type Vstr (Vlen : Integer := 0) is recordtype Vstr (Vlen : Integer := 0) is record Data : String (1 .. Vlen); Data : String (1 .. Vlen);end record;end record;VV : Vstr := (5, “hello”);VV : Vstr := (5, “hello”);

Page 38: An Introduction to Ada Programming Languages Fall 2002

Other TypesOther Types

Derived types (copying a type)Derived types (copying a type)Extended types (object oriented Extended types (object oriented

stuff)stuff)Task types (active threads)Task types (active threads)Protected types (passive Protected types (passive

synchronization)synchronization)More on all these later!More on all these later!

Page 39: An Introduction to Ada Programming Languages Fall 2002

Statement FormsStatement Forms

Assignment statement (is Assignment statement (is notnot an expression) an expression) VariableVariable := := expressionexpression;;

If statementsIf statements ifif conditioncondition thenthen

statementsstatementselsifelsif conditioncondition thenthen statementsstatements……elseelse statementsstatementsend ifend if;;

Page 40: An Introduction to Ada Programming Languages Fall 2002

Statement Forms (cont)Statement Forms (cont)

LoopsLoopsforfor J J inin Integer Integer rangerange 1 .. 10 1 .. 10 looploop

statementsstatementsendend looploop;;

whilewhile condition condition looploop statementsstatementsend loopend loop;;

looploop statementsstatementsend loopend loop;;

Page 41: An Introduction to Ada Programming Languages Fall 2002

Statements (cont)Statements (cont)

Exit statementExit statementexitexit;;

exit whenexit when condition; condition;Can only be used in a loopCan only be used in a loopCan use labels:Can use labels:

Outer : Outer : looploop Inner : Inner : looploop

……exitexit Inner Inner whenwhen Done; Done;

end loopend loop Inner; Inner;end loopend loop Outer; Outer;

Page 42: An Introduction to Ada Programming Languages Fall 2002

Statements (cont)Statements (cont)

Case statementsCase statementscasecase expressionexpression isis

whenwhen 0 => 0 => statementsstatements whenwhen 1 | 10 => 1 | 10 => statementsstatements whenwhen 2 .. 9 => 2 .. 9 => statementsstatementsend caseend case;;

All values in when branches must be All values in when branches must be staticstatic

All possible values of expression must be All possible values of expression must be included exactly onceincluded exactly once

Can use Can use when otherswhen others => to cover rest => to cover rest

Page 43: An Introduction to Ada Programming Languages Fall 2002

Statements (cont)Statements (cont)

Return statementReturn statementreturnreturn;; -- procedure-- procedure

returnreturn expressionexpression;; -- function-- functionOnly in procedure/functionOnly in procedure/functionFunction must have at least one Function must have at least one returnreturn

Raise statementRaise statementraiseraise exception-nameexception-name;;

Page 44: An Introduction to Ada Programming Languages Fall 2002

Declaring and Handling Declaring and Handling ExceptionsExceptions

Declaring an exceptionDeclaring an exceptionError, Disaster : Error, Disaster : exceptionexception;;

Raising an exceptionRaising an exceptionraiseraise Disaster; Disaster;

-- strips stack frames till a handler is -- strips stack frames till a handler is foundfound

Handling an exceptionHandling an exceptionexceptionexception

whenwhen Disaster => Disaster => statementsstatements

Page 45: An Introduction to Ada Programming Languages Fall 2002

More on Exception HandlingMore on Exception Handling

Anywhere we have begin end, we Anywhere we have begin end, we can do:can do:beginbegin

statementsstatementsexceptionexception whenwhen handler => handler => statementsstatements;;

whenwhen handler => handler => statementsstatements;;endend;;

Page 46: An Introduction to Ada Programming Languages Fall 2002

Block StatementBlock Statement

Block statement can be used Block statement can be used anywhereanywheredeclaredeclare -- declare section optional -- declare section optional

declarationsdeclarationsbeginbegin statementsstatementsexceptionexception -- exception section -- exception section optionaloptional handlershandlersendend;;

Page 47: An Introduction to Ada Programming Languages Fall 2002

SummarySummary

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 First assignment will be to do one of

the ACM programming competition the ACM programming competition problemsproblems

You do the program and make test You do the program and make test datadata

Your choice of examplesYour choice of examplesSee website for URLSee website for URL