Demurjian Computer Science amp Engineering Department The University of Connecticut 371 Fairfield Way Box U255 Storrs CT 062693255 StevenDemurjianuconnedu httpwwwengruconnedusteve ID: 815526
Download The PPT/PDF document "Modula-2 Prof. Steven A." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Modula-2
Prof. Steven A. Demurjian Computer Science & Engineering DepartmentThe University of Connecticut371 Fairfield Way, Box U-255Storrs, CT 06269-3255
Steven.Demurjian@uconn.edu
http://www.engr.uconn.edu/~steve
(860) 486–4818 (Office)
(860) 486-3719 (CSE Office)
Slide2Modula-2 Compilers -
https://www.modula2.org/ Available at GNUhttp://nongnu.org/gm2/homepage.html http://nongnu.org/gm2/download.htmlBut Let’s use: https://www.excelsior-usa.com/xds.htmlhttps://github.com/excelsior-oss/xds-ide/releases/tag/xds-ide-1.7.0 Just Extract the zip file to a directory on your desktopModula-2 Online Referenceshttp://www.csc.twu.ca/rsbook/
Slide3http://www.csc.twu.ca/rsbook/
Slide4Overview of Presentation
Modular Programming ConceptsBasics, Variables, ConditionalsLooping, ArraysModules, Procedures/FunctionsUsing the XDS IDE Plus Examples
Slide5What is Modularization?
Modularization Leverages Off of Software Architectural IdeasSW Architectures Decompose System into Interacting Components (Previous Examples)Typically, These Components Exist as Independent Interacting Programs on Hardware PlatformsModularization Explores the Decomposition of These Components into Interacting ModulesModule:Well-defined Component of Software SystemPart of System that Provides Set of Services To Other ModulesServices are Computational Elements Available for Use by Other ModulesModules Publish Services and Import Services
Slide6Example of Modularization
HTSS: High Tech Supermarket SystemCR Contains ModulesUPC ScannerRecord Item SoldReduce InventoryAdd to ReceiptAdd to Profile on CustomerPaymentCouponsCash/Debit/CreditReceipt These Modules Interact with One Another and HTSS Components
Slide7What are Key Modularization Concepts?
What is Tracked for Various Modules?UPC Scanner, Record Item Sold, Payment, ReceiptInterface: Exported for Use by Other ModulesUPC Scanner Exports Scan Function Returns UPC Code, Item Name, PriceItemDB ExportsItemQuery Function Returns Name, Price given UPC Imported for Use by Specific ModuleUPC Scanner Imports ItemQuery Function of ItemDBPayment ImportsFunctions of CreditCard and ATMBankDB Exports
Slide8What Does this Represent?
The Client/Server Paradigm!UPC Scanner – Client that Requests ServicesItemDB – Server that Provides ServicesEstablishes Contract Between Modules!UPC Scanner
ItemDB
Client
Server
Imports from ItemDB
And Other Modules
Exports for use by
UPC Scanner and
Other Modules
USES
Slide9Another Example of Modules
Consider an OS with:File System, Disk I/O Subsystem, DBMSNetwork Server, GUI, Compilers, Desktop ToolsFrom Everyday User Perspective:From Software Engineer Perspective:File System
DBMS
Desktop Tools
GUI
File System
DBMS
Desktop Tools
GUI
Compilers
Network Server
Disk I/O Subsystem
Slide10Impact of Modularization
Pervasive Throughout Software and ComputingClient/Server/Import/Export/USES have ContextsOO/Java – Client/Server Classes, Public Interfaces (Export), Import XX.XX.* (Import), …Web-Based Setting – Client/Server Applications, Clients Use (Import) Services, Servers Provide Services (Export)Middleware – JINI, CORBA, .NETAt Design/Conceptual Level, We Must Understand:What Does Each Module Provide (Export)?What Does Each Module Need (Import)?What Does Each Module Hide (Implementation)?How to Modules Depend on One Another (Uses, Is_Component_Of, and Comprises Relations)
Slide11Modules: Interface vs. Implementation
Interface:Public portion, or the portion accessible outside moduleProvides information about what services the module offersHides how those services are implementedClients only need to see the interface to use the module Module is said to “export” the servicesClient, or the user of the module “imports” the servicesActs as a contract between the module and its clientsImplementation:Private portion, or the portion accessible inside module“How” the exported service is implementedImplementation is hidden from the clients, may be composed of other modules of actual code
Separation of concerns is supported by division between a module’s interface and implementation
Slide12Interface vs. Implementation
To Understand Nature of USES, we Need to Know What a Used Module Exports Through Its InterfaceClient Imports Resources Exported by Its ServersModules Implement Exported ResourcesImplementation Hidden From Clients
interface is like the tip of the iceberg
Slide13Interface, Implementation, and Hiding
In Support of Relations (Uses, Is_Component_Of, and Comprises), Modules ShareVehicle of Sharing: InterfaceSet of Services (Operations) Module Can PerformSubset is Exported for Use by Other ModulesModule Imports Services from Other ModulesInternally, Module Implements Its ServicesSeparation of Concerns:Differentiates Between the Exported Services Operations and Their SignaturesSignature: Name, Parameters and Types, ReturnHidden Implementation that Realizes Services
Slide14Module: Interface vs. Implementation
Symbol
table
GET(Varname) returns hex
PUT(Varname,value) returns hex
NOTIFY(Varname,size)
Retrieve value
Store new value
New entry creation
size = #of entries
it represents
Unnecessary information occurs when
the location of the variable is
returned in GET(Varname).
Slide15Modules: Interface vs. Implementation
Clear distinction of interface and implementation supports rapid prototypingInitial version may be a “quick and dirty” implementation of the service Allowed scope of future changes:Interface must remain unchangedInitial “quick and dirty” version replaced by a more efficient oneNo impact on clients of the modulesEasy to evolve initial prototype into a final product
Slide16Chapter 2.3
Modula 2An Introduction
http://www.etrovub.be/Education/Courses/Progr_Concepts/
Slide17A first example
MODULE
FirstExample;
(* This program computes the area of a circle *)
FROM
InOut
IMPORT
WriteString, WriteLn;
FROM
RealInOut
IMPORT
WriteReal, ReadReal;
CONST
pi =
3.1416
;
VAR
radius, area : REAL;
BEGIN
WriteLn; WriteLn;
WriteString(
"Hello, I compute the area of a circle for you"
);
WriteLn;
WriteString("
Give me the radius in meters
");
ReadReal(radius);
area := pi * radius * radius;
WriteString("The area of this circle is ");
WriteReal(area,0);
WriteString("
square meters
");
WriteLn;
END
FirstExample.
Slide18Terminal Symbols
Upper- and Lower-case lettersa b c d e ... A B C D E ...Digits0 1 2 3 4 5 6 7 8 9Special signs
; , . | + - * /
= # > < ( ) [ ] { }
Composed signs
(* *) := >= <=
Reserved Words
MODULE BEGIN END IMPORT FROM
Source B
Source C
Source D
Source A
Reloc. D
Reloc. A
Reloc. B
Reloc. C
Compiler X
Compiler Y
Assembler
LINKER
Object Code A+B+C+D
Role of a Linker
FROM
InOut
IMPORT
WriteString, WriteLn;
FROM
RealInOut
IMPORT
WriteReal, ReadReal;
Slide20Comments
(* This program computes the area of a circle *)
(*
Text not containing (* nor *)
Text not containing (* nor *)
*)
Comment
Comment
Slide21Constants
Data whose value can not change during program executionLiteral ConstantsOnly a value:Named ConstantsA name and a value:
The value can be a constant expression
3.1416
"The area of this circle is "
pi =
3.1416
twopi = pi *
2.0
Slide22Why named constants ?
Area :=
6
* Length*Length
...
Tax := (Price *
6
) DIV
100
CONST
VAT =
6
;
...
Area :=
6
* Length*Length
...
Tax := (Price *
VAT
) DIV
100
Area :=
21
* Length*Length
...
Tax := (Price *
21
) DIV
100
CONST
VAT =
21
;
...
Area :=
6
* Length*Length
...
Tax := (Price *
VAT
) DIV
100
Constants and Variables
Constants(Name)ValueThe value of aconstant belongsto a type.
Variables
Name
Type
Type =
set of all values
the variable can have
The type determines the internal representation of data
as well as the operations that can be performed on the data
Slide24Assignments
Assignment operator :=Fundamentally different from the = signThe =
sign denotes a timeless relation
The
:=
operator describes a particular action:
The right side expression is evaluated
Its value is stored in the left side variable
Illustrative example :
a := a + 1
area := pi * radius * radius;
Slide25Control Statements
Influence the order of execution of instructionsSelectionIF THEN ELSECASEIterationWHILEREPEATFORLOOP
Procedure Call
WriteString(
"Hello, I comput
WriteLn;
WriteString("
Give me the rad
ReadReal(radius);
area := pi * radius * radius
WriteString("
The area of thi
WriteReal(area,0);
WriteString("
square meters
WriteLn;
Slide26Constants and Variables
ConstantsNameValueThe value of aconstant belongsto a type.
Variables
Name
Type
Type =
set of all values
the variable can have
The type determines the internal representation of data
as well as the operations that can be performed on the data
Slide27Types in Modula 2
Simple Types: values can’t be decomposedOrdinal Types: bijection with natural numbersReals: approx. representation for real valuesPointers: addresses in data memoryStructured Types: Values have # components
Arrays: all components have same type
Records: components can have # types
Sets: small sets of ordinal values
Procedures:
entire subprograms
Slide28Simple Types
Ordinal TypesEnumerated typesBOOLEAN typeCHAR typeCARDINAL typeINTEGER typeSubrange typesREAL TypePOINTER Type
Slide29Enumerated Types
Possible values: User definedTYPE Day = (Monday,Tuesday,Wednesday, Thursday,
Friday, Saturday, Sunday)
Operators : Only relational (= , # , > ,< , >= , <=)
Ordering by enumeration
Day = (Monday,Tuesday,Wednesday, Thursday,
Friday, Saturday, Sunday);
Monday < Sunday
Day = (Sunday, Monday,Tuesday,Wednesday,
Thursday, Friday, Saturday);
Monday > Sunday
Slide30Enumerated Types
Main benefit : ClarityTYPE Sex = (Male, Female);
VAR SexA, SexB : Sex;
...
IF SexA = Male THEN SexB := Female
ELSE SexB := Male
END (* IF *)
Replaces manual encoding
(* Male encoded by 0, Female by 1 *)
VAR SexA, SexB : CARDINAL;
...
SexB := 1 - SexA;
Slide31BOOLEAN Type
Possible values: TRUE , FALSEOperators : NOT, AND, OR
X AND Y
X = TRUE
X = FALSE
TRUE
Y = TRUE
Y = FALSE
FALSE
FALSE
FALSE
X OR Y
X = TRUE
X = FALSE
TRUE
Y = TRUE
Y = FALSE
FALSE
TRUE
TRUE
NOT X
FALSE
X = TRUE
X = FALSE
TRUE
Slide32Relational Expressions
a = b TRUE when a equals ba # b TRUE when a different from ba > b TRUE when a greater than ba < b TRUE when a less than ba >= b TRUE when a greater or equal ba <= b TRUE when a less or equal ba IN b TRUE when value of a belongs to the set b
have a BOOLEAN value
Slide33CHAR Type
Possible values: all characters of a system specific alphabet.In many systems : extended ASCII128 standardized characters + 128 additional characters Various extensions for allowing non-anglosaxon charactersIn new Microsoft & Java systems : UNICODE
65536 different characters, adequate for all languages in the world. ASCII is a subset of UNICODE.
Operators : Only the relational operators
Order can be different in different alphabets.
Relative position of space, letters and digits
VAN ZOERSEL Van Zoersel
VANANTWERPEN van Gorp
Slide34CARDINAL Type
Possible values: implementation dependantWith 16 bit representations : 0 <= C < 216 = 65536With 32 bit representations : 0 <= C < 232 ~ 4.10
9
Operators : relational +
+ addition
- subtraction
* multiplication
DIV integer quotient
MOD integer remainder
Examples :
5 DIV 2 = 2 5 DIV 7 = 0 5 DIV 1 = 5
5 MOD 2 = 1 5 MOD 7 = 5 5 MOD 1 = 0
Slide35INTEGER Type
Possible values: implementation dependantWith 16 bit representations : -215 <= I < 215 = 32768With 32 bit representations : -2
31
<= I < 2
31
~
2.10
9
Operators : relational +
+ addition
- subtraction
* multiplication
DIV integer quotient
MOD integer remainder
Examples :
5 DIV 2 = 2 -5 DIV 2 = -2 5 DIV -2 = -2
5 MOD 2 = 1
-5 MOD 2 = ?? 5 MOD -2 = ??
Internal representation of Integers
Conventions:n = number of bits in representationM = value to be representedM' = value of representationTwo's complement definition:M' = (M + 2n
) MOD 2
n
Range:
- 2
n-1
<= I < 2
n-1
Slide37Subrange Types
For all ordinal types subrange types can be defined TYPE Day = (Mon,Tue,Wed,Thu,Fri,Sat,Sun);
WeekDay = [Mon..Fri];
DayOfMonth = [1..31];
Month = [1..12];
Why Subranges ?
Makes out-of-range detection possible
Allows optimized memory allocation by compiler
Functions and Operators
for ordinal typesThe ORD function returns the internal representation of any ordinal variable as a cardinal value. TYPE
Day = (Mon,Tue,Wed,Thu,Fri,Sat,Sun);
VAR X : Day;
Ch : CHAR;
...
X := Wed;
(* ORD(X) = 2 *)
Ch := "A";
(* ORD(Ch) = 65 *)
Functions and Operators
for ordinal typesThe CHR function returns the character represented internally by a given cardinal value. VAR Ch : CHAR;
n : [0..9];
...
n := 3;
(* Conversion of a cardinal value between 0 and 9 into the corresponding character *)
Ch := CHR(ORD("0")+n);
Functions and Operators
for ordinal typesThe VAL function returns the value in a specified type represented internally by a given cardinal value. TYPE Day = (Mon,Tue,Wed,Thu,Fri,Sat,Sun);
VAR Ch : CHAR;
Today : Day;
...
Today := VAL(Day,2);
(* Wednesday *)
Ch := VAL(CHAR,65);
(* "A" *)
(* VAL(CHAR,n) = CHR(n) *)
Functions and Operators
for ordinal typesThe INC and DEC procedures can be used to increment or decrement ordinal variables. TYPE Day = (Mon,Tue,Wed,Thu,Fri,Sat,Sun);
VAR Ch : CHAR;
Today : Day;
...
Today:=Wed ; INC(Today);
(* Today = Thu *)
C
h := "A"; INC(ch,32);
(* ch = "a" *)
Slide42REAL Type
Approximate representation for real numbers Possible values and accuracy:implementation dependantmajority of computer systems : IEEE754.Single precision (32 bit) "REAL"
Smallest value : 1.18 10
-38
Largest value : 3.39 10
+38
Relative error : < 3.0 10
-8
Double precision (64 bit) "LONGREAL"
Smallest value : 1.18 10
-308
Largest value : 3.39 10
+308
Relative error : < 1.1 10
-16
Slide43REAL Type
Operators and type conversions Arithmetic operators : +, -, *, /Relational operators : =, #,
>, >=, <, <=
Expressions :
No mixing of types
Type conversions:
From REAL to INTEGER :
Truncation !
IntVar := VAL(INTEGER,RealVal);
IntVar := TRUNC(RealVal);
From INTEGER to REAL :
RealVal := VAL(REAL,IntVal);
RealVal := FLOAT(IntVal);
Slide44REAL Type
Example CONST BEFperEURO = 40.3399;VAR
EUROValue : REAL;
BEFValue : CARDINAL;
RealBef : REAL;
.. .
RealBEF := EUROValue * BEFperEURO;
BEFValue := VAL(CARDINAL, RealBEF+0.5)
Slide45Expression Evaluation
Order of evaluation:FactorTermSimple ExpressionExpressionParentheses can modify orderEvaluation is done from left to right,
in a lazy fashion
Slide46Modula 2 Control Statements
Selection statementsBOOLEAN Selector : IF statementOrdinal Selector : CASE statementIteration statementsInitial termination test : WHILE loopFinal termination test : REPEAT loopInfinite loop : LOOPTermination of LOOP : EXIT
Known number of iterations : FOR
PROCEDURE call :
chapter 7
Slide47IF
B THEN S1 ELSE S2 END
B
S2
S1
FALSE
TRUE
B
FALSE
TRUE
S2
S1
Slide48IF
B THEN S END
B
S1
FALSE
TRUE
B
FALSE
TRUE
S1
Slide49IF
B1 THEN S1 ELSIF B2 THEN S2
ELSE
S3
END
S3
S2
B2
FALSE
TRUE
B1
FALSE
TRUE
S3
S1
B1
FALSE
TRUE
S1
S2
FALSE
TRUE
B2
Slide50CASE
e OF a:S1|b:S2|c:S3 END
No
e = a ?
S1
Yes
No
e = b ?
S2
Yes
No
e = c ?
S3
Yes
????
e
S1
S2
e = a
e = b
e = c
S3
Slide51CASE
e OF a:S1|b:S2|c:S3 ELSE S4 END
No
e = a ?
S1
Yes
No
e = b ?
S2
Yes
No
e = c ?
S3
Yes
S4
e
S1
S3
S2
e = a
e = b
e = c
S4
e # a
e # b
e # c
Slide52WHILE
B DO S END
B
S
TRUE
FALSE
S
B
Slide53WHILE examples
WHILE customers in shop DO
serve customer
END
WHILE
NOT end of tape
DO
play a song
END
Slide54REPEAT
S UNTIL B
S
B
S
B
TRUE
FALSE
Slide55REPEAT example
REPEAT Remove bolt
UNTIL
No bolts left
Slide56S
S
LOOP
S1
END
Slide57LOOP example
LOOP Temperature := ReadSensor; IF
Temperature
> MaxTemp
THEN
StopReactor
END
END
Slide58B
S2
TRUE
FALSE
S2
B
S1
S1
LOOP
S1;
IF
B
THEN EXIT
END
; S2
END
Slide59LOOP without EXIT example
Refinement of WHILE example NumberCustomers := CountCustomers;WHILE NumberCustomers > 0
DO
ServeCustomer;
NumberCustomers := CountCustomers
END
Slide60LOOP with EXIT example
LOOP NumberCustomers := CountCustomers; IF
NumberCustomers = 0
THEN
EXIT
END
;
ServeCustomer
END
Slide61FOR statement syntax
(simple version)
Slide62FOR
i := m TO n DO S END
S
m <= n
S
m<=n
TRUE
FALSE
i := m
inc(i)
i = n
TRUE
FALSE
exit loop
when
i = n
i := m
inc(i)
TRUE
Slide63FOR example
FOR NBolt := 1 TO 4 DO
Remove bolt number
NBolt
END
Slide64FOR statement syntax
(complete version)
Slide65FOR example
FOR Count := 10 TO 1 BY -1
DO
SpeakCardinal(
Count
,3)
END;
SpeakString("GO")
Slide66Types in Modula 2
Simple Types: values can’t be decomposedOrdinal Types: bijection with natural numbersReals: approx. representation for real valuesPointers: addresses in data memoryStructured Types: Values have # components
Arrays: all components have same type
Records: components can have # types
Sets: small sets of ordinal values
Procedures:
entire subprograms
Slide67ARRAY applications
MonSun
Sat
Fri
Thu
Wed
Tue
8
19
18
17
16
15
14
13
12
11
10
9
info.
teleN
teleN
st.pr.
teleE
st.pr.
teleE
st.pr.
st.pr.
info.
st.pr.
info.
st.pr.
info.
Slide68ARRAY applications
TYPE
Day = (Mon,Tue,Wed,Thu,Fri,Sat,Sun);
Hour = [8..19];
Course =
ARRAY
[0..10]
OF
CHAR;
Schedule =
ARRAY
Day, Hour
OF
Course;
VAR
RoomK1 : Schedule;
BEGIN
...
RoomK1[Wed,8] := "info.";
...
END
Sieve of Eratosthenes
Print all primes <= Max
Make a set of cardinals 2 <= x <= MAX
FOR all cardinals present in set
Print the first cardinal x
remaining in the set
Remove all multiples of x
from the set
Slide70Sieve of Eratosthenes
Make a set of cardinals 2 <= x <= MAX
CONST
Max = 1000;
VAR
Sieve :
ARRAY
[2..Max]
OF
BOOLEAN;
i : [2..Max];
.. .
FOR
i:= 2
TO
MAX
DO
Sieve[i] := TRUE
END
; (* FOR *)
2
8
7
6
5
4
3
...
FALSE
FALSE
FALSE
FALSE
TRUE
TRUE
TRUE
Slide71Sieve of Eratosthenes
FOR all cardinals present in the set
Print the first cardinal in the set
Remove all multiples of it
VAR
p : CARDINAL;
.. .
FOR
i := 2 TO Max
DO
IF
Sieve[i]
THEN
p := i;
WriteCard(p,5); WriteLn;
WHILE
p <= Max
DO
Sieve[p] := FALSE;
p := p + i
END
(* WHILE *)
END
(* IF *)
END
(* FOR *)
Slide72RECORD example
TYPE
Date =
RECORD
Day : [1 .. 31];
Month : [1 .. 12];
Year : [1900 .. 2100]
END
;
VAR
Today : Date;
Slide73Nested RECORDs example
(1)
TYPE
Date =
RECORD
Day : [1 .. 31];
Month : [1 .. 12];
Year : [1900 .. 2100]
END
;
String =
ARRAY
[0..29]
OF
Char;
Identity =
RECORD
Name, FirstName : String;
BirthPlace : String;
BirthDate : Date;
IssueDate : Date;
END
;
VAR
Myself : Identity;
Today : Date;
Slide74Nested RECORDs example
(2)
Today.Day := 20;
Today.Month := 10;
Today.Year := 1998
Myself.Name := "Tiberghien";
Myself.FirstName := "Jacques";
Myself.BirthPlace := "Berchem";
Myself.BirthDate.Day := 1;
Myself.BirthDate.Month := 4;
Myself.BirthDate.Year := 1946;
Myself.IssueDate := Today;
Slide75Nested RECORDs example
(2)
WITH
Today
DO
Day := 20;
Month := 10;
Year := 1998
END
;
WITH
Myself
DO
Name := "Tiberghien";
FirstName := "Jacques";
BirthPlace := "Berchem";
WITH
BirthDate
DO
Day := 1;
Month := 4;
Year := 1946;
END
;
IssueDate := Today;
END
Slide76Variant RECORD
with explicit tag field
Car =
RECORD
Weight : CARDINAL;
NumberDoors : CARDINAL;
FrameId,EngineId :
ARRAY
[0..19]
OF
CHAR;
Fuel :(Gasoline,FuelOil,LPG,Electricity);
CASE
Engine :
(Explosion,Electricity)
OF
Explosion :
NbrCylinders : CARDINAL;
VolCylinders : CARDINAL
|
Electricity :
Supply : (AC,DC);
Voltage : CARDINAL;
END;
END;
Slide77Variant RECORD
with implicit tag field
Car =
RECORD
Weight : CARDINAL;
NumberDoors : CARDINAL;
FrameId,EngineId :
ARRAY
[0..19]
OF
CHAR;
Fuel :(Gasoline,FuelOil,LPG,Electricity);
CASE
(Explosion,Electricity)
OF
Explosion :
NbrCylinders : CARDINAL;
VolCylinders : CARDINAL
|
Electricity :
Supply : (AC,DC);
Voltage : CARDINAL;
END;
END;
Slide78Summary
SubroutinesProceduresBlock structured languagesScope rulesMemory ManagementProcedure ParametersValue ParametersVariable ParametersOpen Arrays
Function Procedures
Recursion
Slide79Subroutines
CCC
CCC
CCC
DoCCC
DoCCC
Subroutine DoCCC
End DoCCC
Slide80Block Structured Languages
A program is a set of nested blocks
BEGIN ... END BLUE.
BEGIN ... END PURPLE;
BEGIN ... END RED;
BEGIN ... END GREEN;
Slide81Block Structured Languages
An identifier can be used everywhere
within the block where it is declared
VAR A: CARDINAL;
VAR B: REAL;
VAR C: CHAR;
BEGIN ... A:=...; B:=...; C:=...; ... END BLUE.
BEGIN ... A:=...; B:=...; C:=...; ... END PURPLE;
BEGIN ... A:=...; B:=...; C:=...; ... END RED;
BEGIN ... A:=...; B:=...; C:=...; ... END GREEN;
X
X
X
X
Slide82Block Structured Languages
A global identifier can be redefined
The local definition dominates
VAR A: CARDINAL;
VAR B: REAL;
VAR A,C: CHAR;
BEGIN ... A:= 3;... END BLUE.
BEGIN ... A:= 2; B:=...; END PURPLE;
BEGIN ... A:="$"; B:=...; C:=...; ... END RED;
BEGIN ... A:= 1; B:=...;... END GREEN;
Slide83Scope of Procedure Calls
BEGIN…;YELLOW; PURPLE;... END BLUE.
MODULE BLUE
BEGIN …;YELLOW; PURPLE; RED; GREEN;... END PURPLE;
BEGIN …YELLOW; PURPLE; RED; GREEN;... END RED;
BEGIN ... YELLOW; PURPLE; RED; GREEN;... END GREEN;
PROCEDURE PURPLE;
PROCEDURE RED;
PROCEDURE GREEN;
BEGIN …;YELLOW; ORANGE;PURPLE;... END YELLOW;
BEGIN …;YELLOW; ORANGE;PURPLE;... END ORANGE
;
PROCEDURE YELLOW;
PROCEDURE ORANGE;
Slide84Procedure Parameters
CCC abc
CCC uvw
CCC xyz
DoCCC(abc)
DoCCC(uvw)
Subroutine DoCCC(xyz)
End DoCCC
Actual Parameters
Formal Parameters
Slide85Procedure Parameters
Formal parameters are declared in the procedure.Actual parameters appear in the procedure call.Formal and actual parameters MUST have STRICTLY the same type ( = a common type declaration - identical but distinct declarations are not good enough).Association between actual and formal parameters is positional:PROCEDURE DoIt(a,b,c) DoIt(x,y,z)a ~ x ; b ~ y; c ~ z;
Slide86Parameter Passing
Base Register
Data Memory
Calling Block
Activation Record
Called Block
Activation Record
Static
link
Dynamic
links
Actual Parameters
Slide87Value Parameters
The formal parameter is a local variableThe value of the actual parameter is assigned to the formal parameterThe actual parameter can be any expression, as long as its value belongs to the type of the formal parameterAssigning a new value to the formal parameter has no effect on the actual parameter.The formal parameter requires as much memory space as the actual parameter.
Slide88Value Parameters
MODULE
TestValPar (* Parameter passing by Value *);
FROM
InOut
IMPORT
Write,WriteLn;
VAR
x: CHAR;
PROCEDURE
P (c:CHAR);
BEGIN
Write(c)
;
c:='B';
Write(c);
RETURN
END
P;
BEGIN
x:='A';
P(x);
Write(x);
WriteLn
END
TestValPar.
A
B
A
Slide89Variable Parameters
(also called “parameter passing by address”)The formal parameter is the address of a variable.The address of the actual parameter is assigned to the formal parameterThe actual parameter must be a variableAssigning a new value to the formal parameter assigns this value to the actual parameter.The size of the formal parameter in memory is the size of an address (usually 4 bytes)
Slide90Variable Parameters
MODULE
TestValPar (* Parameter passing by Variable *);
FROM
InOut
IMPORT
Write,WriteLn;
VAR
x: CHAR;
PROCEDURE
P (
VAR
c:CHAR);
BEGIN
Write(c)
;
c:='B';
Write(c);
RETURN
END
P;
BEGIN
x:='A';
P(x);
Write(x);
WriteLn
END
TestValPar.
A
B
B
Slide91Computing the GCD
Main MODULE, with parametersMODULE GCD4; ...
VAR
x,y,g : CARDINAL;
PROCEDURE
AskNumber(); ...
END
AskNumbers;
PROCEDURE
ComputeGCD(); ...
END
ComputeGCD;
PROCEDURE
PrintGCD(); ...
END
PrintGCD;
BEGIN
AskNumber(x); AskNumber(y);
ComputeGCD(x,y,g);
PrintGCD(x,y,g);
END
GCD4.
Slide9292
Module/Abstraction ConceptsLocal ModulesAbstract data types and objectsExample : An explicit stack for QuicksortExternal Modules
Definition and Implementation Modules
Separate Compilation of Modules
Libraries
Example : Files and File Sorting
Slide9393
Local Variablesdo not keep their value between activations
PrintNicely;
PrintNicely;
PrintNicely;
PrintNicely;
PrintNicely;
MODULE MainModule
END MainModule.
PROCEDURE PrintNicely;
VAR LineCount : CARDINAL
BEGIN
….
END PrintNicely;
Slide9494
Global Variablesare unavoidable but dangerous ...
PrintNicely;
PrintNicely;
PrintNicely;
PrintNicely;
PrintNicely;
MODULE MainModule
END MainModule.
PROCEDURE PrintNicely;
VAR LineCount : CARDINAL
BEGIN
….
END PrintNicely;
Slide9595
Local Modulesto control accessibility of variables
PrintNicely;
PrintNicely;
PrintNicely;
PrintNicely;
PrintNicely;
MODULE MainModule
END MainModule.
MODULE Print;
EXPORT PrintNicely;
VAR LineCount : CARDINAL
PROCEDURE PrintNicely;
….
END PrintNicely;
BEGIN
(* initialisations *) ….
END Print.
Slide9696
External Modules
DEFINITION MODULE ABC
IMPLEMENTATION MODULE ABC
DEFINITION MODULE UVW
IMPLEMENTATION MODULE UVW
Slide9797
Separate Compilation
DEFINITION MODULE ABC
IMPLEMENTATION MODULE ABC
DEFINITION MODULE UVW
IMPLEMENTATION MODULE UVW
Slide9898
InOut LibraryDEFINITION MODULE InOut;
CONST
EOL = 15C; (* hardware
dependant
--could also be 36C *)
VAR
Done: BOOLEAN;
termCH
: CHAR;
PROCEDURE
OpenInput
(
defext
: ARRAY OF CHAR);
PROCEDURE
OpenOutput
(
defext
: ARRAY OF CHAR);
PROCEDURE
CloseInput
;
PROCEDURE
CloseOutput
;PROCEDURE Read (VAR ch: CHAR);PROCEDURE ReadString
(VAR s: ARRAY OF CHAR);PROCEDURE ReadInt (VAR x: INTEGER);
PROCEDURE ReadCard (VAR x: CARDINAL);PROCEDURE Write (ch
: CHAR);PROCEDURE WriteLn;
PROCEDURE WriteString (s: ARRAY OF CHAR);PROCEDURE WriteInt
(x: INTEGER; n: CARDINAL);
PROCEDURE
WriteCard
(x, n: CARDINAL);
PROCEDURE
WriteOct
(x, n: CARDINAL);
PROCEDURE
WriteHex
(x, n: CARDINAL);
END
InOut
.
Slide99Other Libraries
Slide100Other Libraries
Slide101Other Libraries
Slide102102
Files in Modula 2Files are data structures that reside in peripheral memories, Files are managed by the operating system.Modula 2 doesn't have predefined filesAll Modula 2 implementations offer one or more libraries to access the file system.
The programmer should design his/her own abstract data type implementing files, so that only the implementation module should be adapted to other environments.
Slide103103
A Sequential File Model
Write
Buffer:
Read
File,
in peripheral memory
User program
User program
Buffer:
Slide104104
Natural Merge-SortFiles definitionDEFINITION MODULE MyFiles
;
FROM
FileSystem
IMPORT
File,Create,Rename,Close
,
SetRead,SetWrite,Eof
;
FROM
TextIO
IMPORT
WriteCard,ReadCard
;
TYPE
FileType = RECORD Buffer : CARDINAL;
eof,last : BOOLEAN; F : File;
END; VAR A,B,C :
FileType; PROCEDURE
ResetFile(VAR X:FileType); PROCEDURE
RewriteFile
(VAR X:FileType);
PROCEDURE
CopyItem
(VAR
X,Y:FileType
);
END
MyFiles
.
Slide105105
EXTERNAL MODULESExternal ModulesDefinition and Implementation ModulesSeparate Compilation of Modules
Libraries
Example : Files and File Sorting
Slide106106
External Modules
DEFINITION MODULE ABC
IMPLEMENTATION MODULE ABC
DEFINITION MODULE UVW
IMPLEMENTATION MODULE UVW
Slide107107
Separate Compilation
DEFINITION MODULE ABC
IMPLEMENTATION MODULE ABC
DEFINITION MODULE UVW
IMPLEMENTATION MODULE UVW
Slide108108
Natural Merge-SortFiles definitionDEFINITION MODULE MyFiles
;
FROM
FileSystem
IMPORT
File,Create,Rename,Close
,
SetRead,SetWrite,Eof
;
FROM
TextIO
IMPORT
WriteCard,ReadCard
;
TYPE
FileType = RECORD Buffer : CARDINAL;
eof,last : BOOLEAN; F : File;
END; VAR A,B,C :
FileType; PROCEDURE
ResetFile(VAR X:FileType); PROCEDURE
RewriteFile
(VAR X:FileType);
PROCEDURE
CopyItem
(VAR
X,Y:FileType
);
END
MyFiles
.
Slide109109
Natural Merge-SortMain ProgramBEGIN (* Merge-Sort *)
REPEAT
RewriteFile(A); RewriteFile(B); ResetFile(C);
Distribute;
ResetFile(A); ResetFile(B); RewriteFile(C);
Runs := 0; Merge;
UNTIL
Runs = 1;
END
MergeSort.
Slide110110
Natural Merge-SortDistributePROCEDURE Distribute;BEGIN
REPEAT
CopyRun(C,A);
IF
NOT
C.eof
THEN
CopyRun(C,B)
END
UNTIL
C.eof
END
Distribute;
Slide111111
Natural Merge-SortMerge (1)PROCEDURE Merge;
BEGIN
REPEAT
LOOP
IF
A.Buffer.Key < B.Buffer.Key
THEN
CopyItem(A,C);
IF
A.eor
THEN
CopyRun(B,C)
EXIT END
ELSE
CopyItem(B,C);
IF
B.eor
THEN
CopyRun(A,C) EXIT END END (* IF *) END
; (* LOOP *) Runs := Runs + 1; UNTIL
A.eof OR B.eof;
Slide112112
Natural Merge-SortMerge (2) WHILE NOT A.eof DO
(* copy any possible tail of A *)
CopyRun(A,C); Runs := Runs + 1;
END
;
WHILE NOT
B.eof
DO
(* copy any possible tail of B *)
CopyRun(B,C); Runs := Runs + 1;
END
;
END
Merge;
Slide113113
Natural Merge-SortCopyRunPROCEDURE CopyRun(VAR
X,Y : FileType);
BEGIN
REPEAT
CopyItem(X,Y)
UNTIL
X.eor
END
CopyRun;
Slide114114
Natural Merge-SortFiles definitionDEFINITION MODULE MSFiles;
FROM
FileSystem
IMPORT
File,Create,Rename,Close,
SetRead,SetWrite,Eof;
WriteWord,ReadWord;
TYPE
FileType =
RECORD
Buffer : Item;
eor,eof : BOOLEAN;
F : File;
END
;
VAR
A,B,C : FileType; PROCEDURE ResetFile(VAR X:FileType); PROCEDURE
RewriteFile(VAR X:FileType); PROCEDURE CopyItem(VAR X,Y:FileType);
END MSFiles.
Slide115115
Natural Merge-SortCopyItem implementationPROCEDURE CopyItem(VAR
X,Y:FileType);
BEGIN
Y.Buffer := X.Buffer;
X.Buffer := ReadWord(X.F);
X.eof :=
X.Eof
;
X.eor := X.eof OR
(Y.Buffer.Key > X.Buffer.Key);
WriteWord(Y.F,Y.Buffer);
END
CopyItem;
Slide116116
Natural Merge-SortResetFile implementationPROCEDURE
ResetFile(VAR X:FileType);
BEGIN
WITH
X
DO
Seek(F,0);
Buffer :=
ReadWord
(F);
Last := EOF;
eof := FALSE;
eor := FALSE;
END
END
ResetFile;
Slide117117
Natural Merge-SortRewriteFile implementationPROCEDURE RewriteFile(VAR
X:FileType);
BEGIN
WITH
X DO
Seek(F,0);
Truncate(F);
END
END
RewriteFile;
Slide118EXPORT IN Modula 2
MODULE LocMod2;FROM InOut IMPORT WriteString, WriteInt,
WriteLn
;
VAR Index : CARDINAL;
MODULE
MyStuff
;
IMPORT
WriteString
,
WriteCard
,
WriteLn
;
EXPORT QUALIFIED
WriteStuff
;
VAR Counter : CARDINAL;
PROCEDURE
WriteStuff
;
BEGIN
Counter := Counter + 3;
WriteString
("The value of the counter is "); WriteCard(Counter,8); WriteLn; END WriteStuff;
BEGIN Counter := 4; END MyStuff;
BEGIN (* Main program *) FOR Index := 1 TO 8 DO MyStuff.WriteStuff
; END;END LocMod2.
https://www.modula2.org/tutor/chapter12.php
Slide119DEFINITION Module
DEFINITION MODULE Circles;PROCEDURE AreaOfCircle(Radius : REAL; VAR Area : REAL);PROCEDURE PerimeterOfCircle(Radius : REAL; VAR Perim : REAL);END Circles.
Slide120IMPLEMENTATION Module
IMPLEMENTATION MODULE Circles;PROCEDURE GetPi(VAR Pi : REAL);BEGIN Pi := 3.14159;END GetPi;PROCEDURE AreaOfCircle(Radius : REAL; VAR Area : REAL);
VAR Pie : REAL;
BEGIN
GetPi
(Pie);
Area := Pie * Radius * Radius;
END
AreaOfCircle
;
PROCEDURE
PerimeterOfCircle
(Radius : REAL; VAR
Perim
: REAL);
VAR Cake : REAL;
BEGIN
GetPi
(Cake);
Perim
:= 2.0 * Cake * Radius;
END
PerimeterOfCircle;
BEGIN (* IMPLEMENTATION MODULE body, empty in this case *)END Circles.
Slide121SAMPLE CODE
Slide122Computing the GCD
(1)Specifications :Given two cardinal numbers x and yCompute G, the GCD of x and yAlgorithm : GCD(x, y) = GCD(x, y-x) (x < y) GCD(x, y) = GCD(x-y, y) (x > y)
WHILE x # y
x > y
x := x-y
y := y-x
TRUE
Slide123Computing the GCD
(2)Top level design :Read value of x and yCompute g, the GCD of x and yWrite the value of g
MODULE
GCD1;
...
VAR
x,y,g : CARDINAL;
BEGIN
(* Read value of x and y *)
...
(* Compute g, the GCD of x and y *)
...
(* Write value of g *)
...
END
GCD1.
Slide124Computing the GCD
(3)MODULE GCD1;
FROM
InOut
IMPORT
WriteString,
ReadCard;
VAR
x,y,g : CARDINAL;
BEGIN
(* Read value of x and y *)
WriteString(
"
Enter a cardinal number please
"
);
ReadCard(x);
WriteString(
"
Enter a cardinal number please
"
); ReadCard(y);
(* Compute g, the GCD of x and y *)
... (* Write value of g *) ...
END
GCD1.
Slide125Computing the GCD
(4)MODULE GCD1;
FROM
InOut
IMPORT
WriteString,
ReadCard;
VAR
x,y,g : CARDINAL;
BEGIN
(* Read value of x and y *)
...
(* Compute g, the GCD of x and y *)
WHILE
x # y
DO
IF
x > y
THEN
x := x - y
ELSE y := y - x
END (* IF *)
END
; (* WHILE *)
g := x;
(* Write value of g *)
...
END
GCD1.
Slide126Computing the GCD
(5)MODULE GCD1;
FROM
InOut
IMPORT
WriteString,
ReadCard, WriteCard,
WriteLn;
VAR
x,y,g : CARDINAL;
BEGIN
(* Read value of x and y *)
...
(* Compute g, the GCD of x and y *)
...
(* Write value of g *)
WriteString(
" The GCD of these numbers is : "
);
WriteCard(g,10);
WriteLn
END
GCD1.
Slide127Computing the GCD
(6)MODULE GCD1;
FROM
InOut
IMPORT
WriteString,
ReadCard, WriteCard,
WriteLn,
Read
;
VAR
x,y,g : CARDINAL;
ch : CHAR;
BEGIN
(* Read value of x and y *)
...
(* Compute g, the GCD of x and y *)
WHILE
x # y
DO
WriteString("x = "); WriteCard(x,4); WriteString("; y = "); WriteCard(y,4); WriteLn;
Read(ch);
IF
x > y
THEN
x := x - y
ELSE
y := y - x
END
(* IF *)
END
; (* WHILE *)
g := x;
(* Write value of g *)
...
END
GCD1.
Slide128Computing the GCD
Top level design :Read value of x and yCompute g, the GCD of x and yWrite the value of g
MODULE
GCD1;
...
VAR
x,y,g
: CARDINAL;
BEGIN
(* Read value of x and y *)
...
(* Compute g, the GCD of x and y *)
...
(* Write value of g *)
...
END
GCD1.
Slide129Computing the GCD
with global variablesBEGIN ... END AskNumbers;
BEGIN ... END ComputeGCD;
BEGIN … END PrintGCD;
VAR x,y,g : CARDINAL;
BEGIN AskNumbers; ComputeGCD; PrintGCD END GCD.
PROCEDURE AskNumbers;
PROCEDURE ComputeGCD;
PROCEDURE PrintGCD
MODULE GCD;
Slide130Computing the GCD
Main MODULEMODULE GCD3; ... VAR
x,y,g
: CARDINAL;
PROCEDURE
AskNumbers
; ...
END
AskNumbers
;
PROCEDURE
ComputeGCD
; ...
END
ComputeGCD
;
PROCEDURE
PrintGCD
; ... END PrintGCD;BEGIN AskNumbers
; ComputeGCD;
PrintGCD; END
GCD3.
Slide131Computing the GCD
PROCEDURE AskNumbersPROCEDURE AskNumbers;
BEGIN
(* Read value of global variables x and y *)
WriteString
(
"
Enter a cardinal number please
"
);
ReadCard
(x);
WriteString
(
"
Enter a cardinal number please
"
);
ReadCard
(y);
END
AskNumbers;
Slide132Computing the GCD
PROCEDURE ComputeGCDPROCEDURE ComputeGCD;
(* Computes g, the GCD of x and y *)
(*
x,y
and g are global CARDINAL variables *)
BEGIN
WHILE
x # y
DO
IF
x > y
THEN
x := x - y
ELSE
y := y - x
END
(* IF *)
END
; (* WHILE *)
g := x;END
ComputeGCD;
Slide133Computing the GCD
PROCEDURE PrintGCD PROCEDURE PrintGCD;
(* Write value of global variable g *)
BEGIN
WriteString(
" The GCD of these numbers is : "
);
WriteCard(g,10);
WriteLn
END
PrintGCD;
Slide134Computing the GCD
Main MODULE, with parametersMODULE GCD4; ... VAR
x,y,g
: CARDINAL;
PROCEDURE
AskNumber
(); ...
END
AskNumbers
;
PROCEDURE
ComputeGCD
(); ...
END
ComputeGCD
;
PROCEDURE
PrintGCD
(); ... END PrintGCD;BEGIN AskNumber
(x); AskNumber(y); ComputeGCD
(x,y,g);
PrintGCD(x,y,g); END
GCD4.
Slide135Computing the GCD
Main MODULE, with function proceduresMODULE GCD5; ... VAR
x,y,g : CARDINAL;
PROCEDURE
AskNumber():CARDINAL;
...;
PROCEDURE
ComputeGCD():CARDINAL;
...;
PROCEDURE
PrintGCD(); ...
END
PrintGCD;
BEGIN
x
:=
AskNumber(); y
:=
AskNumber();
g
:=
ComputeGCD(x,y); PrintGCD(x,y,g); END GCD5.
Slide136Computing the GCD
Main MODULE, with function proceduresMODULE GCD6; ... VAR
x,y
: CARDINAL;
PROCEDURE
AskNumber
():CARDINAL;
...;
PROCEDURE
ComputeGCD
():CARDINAL;
...;
PROCEDURE
PrintGCD
(); ...
END
PrintGCD
;BEGIN
x := AskNumber(); y := AskNumber
(); PrintGCD(x,y
, ComputeGCD(x,y)
); END GCD6.
Slide137Computing the GCD
Function PROCEDURE AskNumberPROCEDURE AskNumber():CARDINAL;
VAR n : CARDINAL;
BEGIN
(* Reads value of a variable parameter n *)
WriteString
(
"
Enter a cardinal number please
"
);
ReadCard
(n);
RETURN
n
END
AskNumber
;
Slide138Computing the GCD
PROCEDURE ComputeGCDPROCEDURE ComputeGCD(x,y:CARDINAL):CARDINAL; (* Computes the GCD of x and y *)
BEGIN
WHILE
x # y
DO
IF
x > y
THEN
x := x - y
ELSE
y := y - x
END
(* IF *)
END
; (* WHILE *)
RETURN
x;
END
ComputeGCD;
Slide139Computing the GCD
PROCEDURE PrintGCD PROCEDURE PrintGCD(x,y,g:CARDINAL);
(* Write value of parameters x,y and g *)
BEGIN
WriteString(
" The GCD of "
);
WriteCard(x,1);
WriteString(
" and "
);
WriteCard(y,1);
WriteString(
" is : "
);
WriteCard(g,1);
WriteLn
END
PrintGCD;
Slide140Side Effects
Functions are intended for computing a value, and nothing else!Functions can modify global variables and VAR parameters.Such modifications are "Side Effects"Side effects should be avoided.Some functions also perform Input/Output operations. Such side effects are harmless.
Slide141Computing the GCD
PROCEDURE ComputeGCD, With side effectPROCEDURE ComputeGCD(VAR
x,y:CARDINAL
):CARDINAL;
(* Passing x and y by
VARiable
causes a side effect *)
(* Computes the GCD of x and y *)
BEGIN
WHILE
x # y
DO
IF
x > y
THEN
x := x - y
ELSE
y := y - x
END
(* IF *)
END
; (* WHILE *) RETURN x;
END ComputeGCD;
Slide142Computing the GCD
Function PROCEDURE AskNumberPROCEDURE AskNumber():CARDINAL;
BEGIN
(* Reads value of a variable parameter n *)
(* The following statement can be considered
as a harmless side effect *)
WriteString
("Enter a cardinal number please ");
ReadCard
(n);
RETURN
n
END
AskNumber
;
Slide143Computing the GCD
PROCEDURE AskNumberPROCEDURE AskNumber( VAR n:CARDINAL); BEGIN
(* Reads value of a variable parameter n *)
WriteString(
"
Enter a cardinal number please
"
);
ReadCard(n);
END
AskNumber;
Slide144Computing the GCD
PROCEDURE ComputeGCDPROCEDURE ComputeGCD(x,y:CARDINAL; VAR g:CARDINAL); (* Computes g, the GCD of x and y *)
BEGIN
WHILE
x # y
DO
IF
x > y
THEN
x := x - y
ELSE
y := y - x
END
(* IF *)
END
; (* WHILE *)
g := x;
END
ComputeGCD;
Slide145Computing the GCD
PROCEDURE PrintGCD PROCEDURE PrintGCD(x,y,g:CARDINAL);
(* Write value of parameters x,y and g *)
BEGIN
WriteString(
" The GCD of "
);
WriteCard(x,1);
WriteString(
" and "
);
WriteCard(y,1);
WriteString(
" is : "
);
WriteCard(g,1);
WriteLn
END
PrintGCD;