56
An Introduction to An Introduction to Ada Ada Programming Languages Programming Languages Spring 2004 Spring 2004

An Introduction to Ada Programming Languages Spring 2004

  • View
    218

  • Download
    0

Embed Size (px)

Citation preview

An Introduction to AdaAn Introduction to Ada

Programming LanguagesProgramming Languages

Spring 2004Spring 2004

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

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

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;

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

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;

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

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;

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;

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;

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

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;

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)

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

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;

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;

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

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

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;;

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

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

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;

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.

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

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.

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.

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; ;

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)

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

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);

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;

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;

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;

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

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

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!

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”);

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!

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;;

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;;

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;

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

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;;

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

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;;

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;;

Back to PackagesBack to Packages

Private types and private partsPrivate types and private partsA type can be declared privateA type can be declared private Implementation is hiddenImplementation is hiddenBut can provide subprograms that But can provide subprograms that

operate on instances of the typeoperate on instances of the type

A Package for StacksA Package for Stacks package Stacks ispackage Stacks is type Stack is private;type Stack is private; procedure Push (It : Character; On : in out Stack);procedure Push (It : Character; On : in out Stack); procedure Pop (It : Character; From : in out Stack);procedure Pop (It : Character; From : in out Stack); function Empty (S : Stack) return Boolean;function Empty (S : Stack) return Boolean; Stack_Empty : exception;Stack_Empty : exception;

Stack_Full : exception;Stack_Full : exception; privateprivate type Stack is recordtype Stack is record top : Integer := 0;top : Integer := 0; contents : String (1 .. 80) := (others => ‘*’);contents : String (1 .. 80) := (others => ‘*’); end record;end record; end Stacks;end Stacks;

A client of StacksA client of Stacks

with Stacks;with Stacks;package Mumbo ispackage Mumbo is

…………S : Stacks.Stack;S : Stacks.Stack;……Stacks.Push (‘x’, S);Stacks.Push (‘x’, S);……exceptionexception when Stacks.Stack_Full => when Stacks.Stack_Full => … …

end Mumbo;end Mumbo;

A client of StacksA client of Stacks

with Stacks; use Stackswith Stacks; use Stackspackage Mumbo ispackage Mumbo is

…………S : Stack;S : Stack;……Push (‘x’, S);Push (‘x’, S);……exceptionexception when Stack_Full => when Stack_Full => … …

end Mumbo;end Mumbo;

Implementation of StacksImplementation of Stacks

package body Stacks ispackage body Stacks is procedure Push (It : Character; On : in out procedure Push (It : Character; On : in out

Stack) isStack) is begin begin if On.top = 80 then if On.top = 80 then raise Stack_Full; raise Stack_Full; else else On.top := On.top + 1; On.top := On.top + 1; On.contents (On.top) := It; On.contents (On.top) := It; end if; end if; end Push; end Push;

… … end Stacks;end Stacks;

Generic PackagesGeneric Packages genericgeneric type T is private;type T is private;

Max : Natural; Max : Natural; package Stacks ispackage Stacks is type Stack is private;type Stack is private; procedure Push (Thing : T ; On : in out Stack);procedure Push (Thing : T ; On : in out Stack); … … privateprivate type Arr is array (1 .. Max) of T;type Arr is array (1 .. Max) of T; type stack is recordtype stack is record Top : Integer := 0;Top : Integer := 0; contents : Arr;contents : Arr; end record; end record; end Stacks;end Stacks;

Implementing genericImplementing generic

Generic body looks just like the non-Generic body looks just like the non-generic onegeneric one

Except that we will reference type T Except that we will reference type T instead of type Character.instead of type Character.

Client of GenericClient of Generic

with Stacks;with Stacks;package Mumbo ispackage Mumbo is -- Must first instantiate the package -- Must first instantiate the package package Istak is new Stacks (Integer, package Istak is new Stacks (Integer, 100);100); S : Istak.Stack; S : Istak.Stack; … … Istak.Push (219, S); Istak.Push (219, S); … …end Mumbo;end Mumbo;

Summary and Ada Summary and Ada AssignmentAssignment

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 problemsproblemsfrom the 2001 internationalfinals. from the 2001 internationalfinals. ((http://icpc.baylor.edu/past/icpc2001/Fhttp://icpc.baylor.edu/past/icpc2001/Finals/Problems.pdfinals/Problems.pdf))

There are nine problems, you can do There are nine problems, you can do any one of them you choose.any one of them you choose.

More on the AssignmentMore on the Assignment

Hand in Ada source codeHand in Ada source codeTest results including those in the problem Test results including those in the problem

and at least one other example setand at least one other example setTry to use the features of Ada (particularly Try to use the features of Ada (particularly

package structure) to good use.package structure) to good use.Try to extract reusable packages for the Try to extract reusable packages for the

problem (which could be used in other problem (which could be used in other similar problems).similar problems).

Due date: March 2Due date: March 2ndnd