Modula-2 (на английском языке) (1161147), страница 4
Текст из файла (страница 4)
Set intersection is equivalent to a bit-by-bit AND operation.
Set symmetric difference is equivalent to a bit-by-bit XOR operation.
Relational operators
These operators are the arithmetic comparison operators and the set inclusion and membership operators.
= | equal |
(<>, #) | not equal |
< | less |
> | greater |
<= | less or equal, set inclusion |
>= | greater or equal, set inclusion |
IN | set membership |
The six arithmetic relations apply to all signed and unsigned integer types, REAL, LONGREAL, BOOLEAN, CHAR, and enumeration types.
-
The equal and not equal operators also apply to SET, POINTER, COMPLEX, LONGCOMPLEX and procedure types.
-
A <= B, where A and B are compatible sets indicates that B contains all of the elements of A, that is, A is a subset of B.
-
A >= B, where A and B are compatible sets indicates that A contains all the elements of B, that is, B is a subset of A.
-
A IN B, where B is a set type and A is a value in the base type of the set, indicates that element A is in the set B.
-
All the relational operators produce results of type BOOLEAN.
Order of Evaluation
A precedence is associated with each operator that determines the order in which operators are applied in an expression. Operators of higher precedence are applied before operators of lower precedence. Operators of the same precedence are evaluated in left-to-right order.
You can use parentheses in an expression to override the order of evaluation. A parenthesized expression is always completely evaluated before being used as an operand.
There are four levels of precedence for Modula-2 operators. They are, from highest to lowest:
Level 4: NOT ~
Level 3: * / REM DIV MOD AND &
Level 2: + - OR
Level 1: < <= = >= > <> # IN
Examples:
2 + 3 * 5
equals 17, not 25, because the multiplication operator (*) has higher precedence than the addition.
(2 + 3) * 5
equals 25 because the parentheses force the addition to be performed before the multiplication.
Statements
Statements denote actions. There are elementary and structured statements. Elementary statements are not composed of any parts that are themselves statements. They are the assignment, the procedure call, and the return and exit statements. Structured statements are composed of parts that are themselves statements. These are used to express sequencing, and conditional, selective, and repetitive execution.
statement = [assignment | ProcedureCall |
IfStatement | CaseStatement | WhileStatement |
RepeatStatement | LoopStatement | ForStatement |
WithStatement | EXIT | RETURN [expression] ].
A statement may also be empty, in which case it denotes no action. The empty statement is included in order to relax punctuation rules in statement sequences.
Statement Sequences
Statement sequences denote the sequence of actions specified by the component statements which are separated by semicolons.
StatementSequence = statement {";" statement}.
Assignments
The assignment serves to replace the current value of a variable by a new value indicated by an expression. The assignment operator is written as ": =" and pronounced as "becomes".
assignment = designator": =" expression.
The designator to the left of the assignment operator denotes a variable. After an assignment is executed, the variable has the value obtained by evaluating the expression.
The old value is lost (overwritten). The type of the variable must be assignment compatible with the type of the expression. Operand types are said to be assigrunent compatible, if either they are compatible or both are INTEGER or CARDINAL or subranges with base types INTEGER or CARDINAL.
A string of length n1 can be assigned to a string variable of length n2 > n1. In this case, the string value is extended with a null character (OC). A string of length 1 is compatible with the type CHAR.
Examples of assignments:
i := k
p := i=j
j := log2(i + j)
F := log2
s := {2,3,5,7,1l,13}
a[i] : = (i + j) * (i-j)
t1^.key:= i
w[i+l].ch:= "A"
Procedure Calls
A procedure call serves to activate a procedure. The procedure call may contain a list of actual parameters which are substituted in place of their corresponding formal parameters defined in the procedure declaration. The correspondence is established by the positions of the parameters in the lists of actual and formal parameters respectively. There exist two kinds of parameters: variable and value parameters.
In the case of variable parameters, the actual parameter must be a designator denoting a variable. If it designates a component of a structured variable, the selector is evaluated when the formal/actual parameter substitution takes place, i.e. before the execution of the procedure. If the parameter is a value parameter, the corresponding actual parameter must be an expression. This expression is evaluated prior to the procedure activation, and the resulting value is assigned to the formal parameter which now constitutes a local variable. The types of corresponding actual and formal parameters must be identical in the case of variable parameters, or assignment compatible in the case of value parameters.
ProcedureCall = designator [ActualParameters].
Examples of procedure calls:
Read(i);
Write(j*2 + 1 , 6)
INC(a[i])
IF Statements
IfStatement = IF expression THEN StatementSequence
{ELSIF expression THEN StatementSequence}
[ELSE StatementSequence] END.
The expressions following the symbols IF and ELSIF are of type BOOLEAN. They are evaluated in the sequence of their occurrence, until one yields the value TRUE. Then its associated statement sequence is executed. If an ELSE clause is present, its associated statement sequence is executed if and only if all Boolean expressions yielded the value FALSE.
Example:
IF (ch>= "A") & (ch <= "Z") THEN ReadIdentifler
ELSIF (ch > = "0") & (ch < = "9") THEN ReadNumber
ELSIF ch = '"' THEN ReadString('"')
ELSIF ch = "'" THEN ReadString("'")
ELSE SpecialCharacter
END
Case Statements
Case statements specify the selection and execution of a statement sequence according to the value of an expression. First the case expression is evaluated, then the statement sequence is executed whose case labelllst contains the obtained value. The type of the case expression must be a basic type (except REAL), an enumeration type, or a subrange type, and all labels must be compatible with that type. Case labels are constants, and no value must occur more than once. If the value of the expression does not occur as a label of any case, the statement sequence following the symbol ELSE is selected.
CaseStatement = CASE expression OF case {"|" case}
[ELSE StatementSequence] END.
case = [CaseLabelList ":" StatementSequence].
Example:
CASE i OF
O : p := p OR q; x := x+y |
1 : p := p OR q; x := x-y |
2 : p := p AND q; x := x*y
ELSE
END
While statements
While statements specify the repeated execution of a statement sequence depending on the value of a Boolean expression. The expression is evaluated before each subsequent execution of the statement sequence. The repetition stops as soon as this evaluation yields the value FALSE.
WhileStatement = WHILE expression DO StatementSequence END.
Examples:
WHILE j > 0 DO
j:= j DIV 2;
i:= i+1
END
WHILE i#j DO
IF 1 > j THEN i : = i-j
ELSE j:= j-i
END
END
WHILE (t # NIL) & (t^.key # i) DO
t : = t^.left
END
Repeat Statements
Repeat statements specify the repeated execution of a statement sequence depending on the value of a Boolean expression. The expression is evaluated after each execution of the statement sequence, and the repetition stops as soon as it yields the value TRUE. Hence, the statement sequence is executed at least once.
RepeatStatement = REPEAT StatementSequence UNTIL expression.
Example:
REPEAT
k := i MOD j;
i := j;
j := k;
UNTIL j = 0
For Statements
The for statement indicates that a statement sequence is to be repeatedly executed while a progression of values is assigned to a variable. This variable is called the control variable of the for statement. It cannot be a component of a structured variable, it cannot be imported, nor can it be a parameter. Its value should not be changed by the statement sequence.
ForStatement = FOR ident ": =" expression TO expression
[BY ConstExpression] DO StatementSequence END.
The for statement
FOR v:= A TO B BY C DO SS END
expresses repeated execution of the statement sequence SS with v successively assuming the values A, A + C, A + 2C, ... , A + nC, where A + nC is the last term not exceeding B. v is called the control variable, A the starting value, B the limit, and C the increment A and B must be compatible with v; C must be a constant of type INTEGER or CARDINAL. If no increment is specified, it is assumed to be 1.
Examples:
FOR i : = 1 TO 80 DO j : = j + a[i] END
FOR i := 80 TO 2 BY -1 DO a[i]:= a[i-1] END
Loop Statements
A loop statement specifies the repeated execution of a statement sequence. It is terminated by the execution of any exit statement within that sequence.
LoopStatement = LOOP StatementSequence END.
Example:
LOOP
IF t1^.key > x THEN
t2 := t1^.left; p:= TRUE
ELSE
t2 := t1^.right; p:= FALSE
END;
IF t2 = NIL THEN
EXIT
END;
t1=t2
END
While, repeat, and for statements can be expressed by loop statements containing a single exit statement. Their use is recommended as they characterize the most frequently occurring situations where termination depends either on a single condition at either the beginning or end of the repeated statement sequence, or on reaching the limit of an arithmetic progression. The loop statement is, however, necessary to express the continuous repetition of cyclic processes, where no termination is specified. It is also useful to express situations exemplified above. Exit statements are contextually, although not syntactically bound to the loop statement which contains them.
With statements
The with statement specifies a record variable and a statement sequence. In these statements the qualification of field identifiers may be omitted, if they are to refer to the variable specified in the with clause. If the designator denotes a component of a structured variable, the selector is evaluated once (before the statement sequence). The with statement opens a new scope.
WithStatement = WITH designator DO StatementSequence END.
Example:
WITH t^ DO
key:= 0; left:= NIL; right:= NIL
END
Return statements
A return statement consists of the symbol RETURN, possibly followed by an expression. It indicates the termination of a procedure (or a module body), and the expression specifies the value returned as result of a function procedure. Its type must be assignment compatible with the result type specified in the procedure heading.
Function procedures require the presence of a return statement indicating the result value. There may be several, although only one will be executed. In proper procedures, a return statement is implied by the end of the procedure body. An explicit return statement therefore appears as an additional, probably exceptional termination point.
An exit statement consists of the symbol EXIT, and it specifies termination of the enclosing loop statement and continuation with the statement following that loop statement.
Procedure declarations
Procedures are sequences of instructions that perform a specific task. Usually, procedures are used when the same sequence of code is required more than once in a program. In this case, the procedure is written once and is called from several places.
Procedures also improve the clarity of a program. A complicated task is easier to understand if it is composed of a sequence of sub tasks, each implemented by a procedure.
To make procedures more flexible, they can take parameters, which are data objects that can vary from one call to the next. This lets you specify an algorithm with a procedure that is run with different data at different times.
Procedure Declarations
The procedure declaration takes the following form:
PROCEDURE identifier [(Formals) [:ReturnType]]; [ FORWARD ]
[Body]
The identifier is the name of the procedure.
Formals are specified by:
[FormalSection {; FormalSection}]
where FormalSection is:
[VAR identifier {,identifier}: [ARRAY OF {ARRAY OF}] FormalType
FormalType is a type name, and may be qualified by a module name.
If ReturnType is specified, the procedure is a function procedure. A function procedure is a procedure that returns a value, and can be used in expressions. ReturnType is the name of the type of value that the procedure returns.
Note that on function procedures, the parentheses of the parameter list are required even if there are no parameters.
Body takes the following form:
{declaration}[BEGIN ListOfStatements [EXCEPT ListOfStatements]] END identifier;
The body of the procedure is a block that is executed when the procedure is called. The normal execution body consists of the ListOfStatements between the BEGIN keyword and the EXCEPT keyword if present or the END keyword if EXCEPT is not present. If the EXCEPT keyword is present then the ListOfStatements between the EXCEPT keyword and the END keyword for the procedure are the exception execution body of the procedure. If the procedure declaration is in a definition module, the body is not included.
The identifier at the end of the body must be the same as the name of the procedure.