0% found this document useful (0 votes)
89 views

The Simscript Programming Language: P. Kivict. R. Villanueva Ant, H. M. Markowitz

Lenguaje de simulacion SimScript
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

The Simscript Programming Language: P. Kivict. R. Villanueva Ant, H. M. Markowitz

Lenguaje de simulacion SimScript
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 394

The SIMSCRIPT II Programming Language

P. J. Kivict. R. Villanueva ant, H. M. Markowitz

October 1968

R-460-PR

A REPORT PREPARED FO ..

UNITED STATES AIR FORCE PROJEC'PRAND

Ill*O ma.. S -* loth *


MOnI, ca . pI@lNWa * *Oaa.
Copyright 0 1968
THE RAND CORPORATION

This Rand Memorandum io p.res ed as & competent ,armlqen of O.. subject.


worthy of publiartiw., The Rand Cnrporstiann muwhe. for the quality of the
reulrrh. without neqcnamlnk ..ndoring thr opainiofi and elm-riofns nl the

Pubished by The RAND Cx•apxoron


-ili-

PREFACE

SIVSCRIPT II is a general programing language that should be of


interest to people in the data pro, ,ing and computer programing
comnunity, particularly those involved in the simulation of industrial,
military, and social systems.
RAND's principal interest in developing SIMSCRIPT II was to en-
hance the discrete-event simulation capability of both RAND and its
clients. The language has been designed to facilitate the simulation
of large, complex systems, and to reduce the total time spent in de-
signing, prograimng, and testing simulation models. Design and
development have been carried out in two stages: language design
and compiler implementation. This Report describes the SIMSuRIPT II
language only; its companion study, P. J. Kiviat, H. J. Shukiar,
J. B. Urman, and R. Villanueva, The SIMSCRTPT II Pmgroaving Lan-
gtiage. IBM 360 Imptementation, RM-5777-PR, describes RAND's IBM 360
implementation of the language.
In developing SIIMCRIPT II, user considerations were pararnount.
For this reason, the language is free-form and Englisn-like. Also,
its compiler is "forgiving," in the sense that it corrects a large
percentage of user syntax errors and forces execution of every com-
plete program that is submitted. The combination of a free-form,
English-like language, a forgiving compiler, and forced program exe-
cution greatly reduces the nuer of times a program must be submitted
to get it to perform properly. To make the process even more efficient,
a number of debuging statements and program control features &te also
provides.
This re•'earh is supported bIy the I'nited States .Air Force unler Project I AND-(.or.
tract No. F 1162(0-t67-.( -AMSI.• moi tornied bv the D)irecto)ratte of O)tpe'rational RHequiremren ts
and Di' elopmert Pliz . l)epult (Chie of-.Staff. Researc h antd Dr'e elopru•i•it. Ftq .iq+F.
Vis, or (concluio.ns conitainied in thi. .tudv should not be interpreteild i reprrenting
the o(ffeial olpinion or poli'+ of the I'nited States Air Force.

DISTRIBUTION STATE.MENT
Thi. diurmrt hjI. le)ppro•ed for pullic rel•eacs drl ,ale:
it, d trilutii i '. irullinited.

A IW

"-.'.m• w
S*•MMARY

SIMSCRIFT II is a rich and versatile computer prograimming laaguag'


designed primarily for discrete-event simulation applications, but
equally well suited to general programming problems. This Report,
which describes the SIMSCRIPT II language, is divided into chapters
corresponding to language "levels," which provide a functional path
through the language:

Level 1: A simple teaching language designed to introduce pro-


gramning concep's to nonprogrammers.
Level 2: A language roughly comparable in power with FORTRAN,
but departing greatly from it in specific features.
Level 3: A language roughly comparable in power to ALGOL or
PL/I. but again with many specific differences.
Level 4: That part of SIMSCRIPT II that contains the entity-
attribute-set features of SIMSCRIPT. These features
have been updated and augmented to provide a more
powerful list-processing capability.
Level 5: The simulati)n-oriented part of SIMSCRIPT I1, containing
statements fur time advance, event and activity pro-
cessing, generation of statistical variares, and a-.
mulation and analysis of simulation-genecated data.

Except for some basic knowledge concerning what a computer is end what
a programing language translator (compiler) does, no prior computer
education or programing knowledge on the reader's part has been
"*used. As a result, the Report will not have equal appeal to all
readers. Professional programers vill find it slow reading at first;
novices may wish it read more slowly. To reduce the discomfort of
either too slow or too rapid a pace through all of SIMSCRIPT I1,wV
suggest a selective path through the Report. Stctions that a,- un-.
usually difficult or contain features of powerful but limited use a-,e
-vi-

marked with an asterisk, ard should probably be skipped on first read-


ing by all but the most professional of programmers -- who will probably
want to read thede sections first to see what SIMSCRIPT II has to offer.
Since SIMSCRIPT II is a "large" language, thio is a long document.
The authors hope its lt'gth is justified by the mode of presentation
chosen, which meets the need for a teaching as well as a reference
manual. Once this Report has been mastered, RM-5776-PR, The SIMSCRIPT
II Progrwwmping Language: Refernce Manu.7l will he a useful guide.
Since this Report documents a language rather than an implemen-
tation, still another work is required to describe the operational
characteristics of the RAND IBM 360 SIMSCRIPT II compiler. This work,
The SIDCRI`PT II Programing Language: IBM 360 Implementation,
RM-5777-PR, describes the specific features of the IBM 360 compiler,
the procedu-es necessary for its use, the error messages it generates
during compilation and execution, and so on.

i
-vii-

ACXNOWLED04ENTS

We owe a great deal to and would like to acknowledge the con-


tributicns of George Benedict and Bernard Hausner, who, as early am-
bers of the project, did much of the basic compiler design and pro-
graming. They created the foundation upon which we have built.
Similarly, we are indebted to Joel Urman of the IBM Corporation, who,
while progrming all of the input/output and operating system inter-

face routines for the IBM 360 compiler, influenced our language de-
sign.
SISCRIPT II having turned out to be more than just an extended
SIMSCRIPT, wv want to acknovledge the contributions of many friends --
compiler writers, language designers, and programers -- who have in-
teracted with us over the y'_•rs. Some of their suggestions are re-
flected in the simulation-oriented sections of the language. Much
of their influence is seen in the part of SIMSCRIPT II that can be
called a "general programing language." We would like to thank
Bob Balser, John Buxton, John Laski, Howard Krasnov, John McNelsy,
Kristen Nygaard, and Paula Oldfather for their suggestions and crit-
icisms. Should they, or any others, perceive glints of their own
ideas in SIMSCILIFT II. they should not be surprised.
Lastly. wa wish to thank X. J. Shukisr for the many helpful sug-
gestions he made whila reviewing the manuscript and using early vor-
sions of the compiler. Sally Anderson labored over the Index, for
which we are truly Mrateful.
-ix-

CONTENTS

PREFACE .......................... *............................. iIii

SUIMMARY ........................... ......................... .v

ACKNOWLEDGMENTS ............................................... vii

Chr.pter 1
SIM CRIPT II: Level 1 ......................................
1-00 Introduc tion .................................. .... 1
1-01 Vara Zb#e ............... .......... ......... . .... ... .
1-02 Const ts ................................... .... 2
1-03 Arithmetic Expreseions ............................. 2
1-04 Logical Expressions ................................ 5
1-05 Readinq Data from Punched Carde .................... 6
1-06 Skipping Lu.wantcd Data ............................. 7
1-07 Computing Variable Values .......................... 9
1-08 Specialized Cof:,tation Statementa ................. 9
1-09 A Pgra on cards and the F" of Comprtatian ... 10
1-10 Clarifying C'omir- .'n a Pmq*r ................... 12
i-il Chaning the Flow of Computation y Direct Oier 13
1-12 Chwiging the FZot of Computation by
Loqia! Expresion ............................ 13
2-13 Displaying the Results of Cc•utation ............... 17
1-14 The Logical Endof aProlrG I ....................... ?
1-15 The Phyuical End of a Progr ...................... 2'
1-16 Some '72pTe SI.CCRIPT II, Lev 1 PAogrxm ......... 21

Chapter 2
SIMSCRIPT II: Level 2 .................................... 28
2-00 Variab'* and L&*•Z YVtw, Peesee.................. 28
r- :ab,U .4o d e ..................................... 29
"2, icbl
va" ... ............... 31
- SCbe'ipe: . ,rr ................................. 33
-::•4 S e'r • ............................. 40

a
?_1.... ; witpe................................ 4
-A.Y~i '~tdjtra ee 11!-.8
-,,.. Te................................ 48

":-: p, . ,f , ;............................... 76
-:4 3:e:e~'-2 Lab*:*.• .............................. 78
-I--

2-1S The Struoture of a SI3CRIPT II Program ............. 79


2-16 Subprogrm Definition............................. 82
2-1? Routines Used as Function .......................... 88
2-78 LibarPF•,•ctions ................................... 90
2-l9 F'rogi'ram-DefinedFusnctionse ............... 92
2-20 Routine Used as More General
Comwputational Procaeduree . ........... 99
2-21 Routines Used as Funotions and as Proceduree ........ 102
2-22 Arra Pointer# as Routine Argentse ................. 103
2-23 Returning Reserved Arrase to Free Storage ........... 110
2-24 Global Variablee, Routines, an Side Effects ........ 112
" 2-26 Recisriv RoutinRes ....................... ..... 113
2-26 Definition of Synonymous Naews and Open Routines .... 120
2-27 Sample SIWCRIFT IT, LeveL 2 Programs ............... 124
2-28 More on Program ForPwtu ............................. 129

Chapter 3
SI[SCRIPT II: Level 3
3-00 A Statement for SimpZiffyiin Nes el7 Statiments .... 131
3-01 A Statement for SimpLifying NVested DO Loops ......... 132
3-02 Cp 'fying Complex Logical Expr•asione............... 134
3-03 Logical Control Prase .............................. 137
3-04 Returning Routines to Free Store ................. 1 40
.- 05 External Srorze vid Retrieval of Routines .......... 142
3-06 A Sea-rc Statem nr .................................. 145
3-0' A Statmnt for Camuting Sow. StandarI
Y%*tctionB of vari-blea .......................... 147
3-08 Alpha--A Ye wMode ................................... 150
3-09 A Formwtte'd Inout/Output Statement .................. 153
3-121 MiEcezza-.o'•u fnput/9•utut Staterwnts
and Fa-.Zt CiO8 .... .............................. 173
3_7- 1 F.j 'ýing
1rtrz .~fIo'ai'......................176

3-1
- WritrYnc Fo t:e .Reprts ................................ 179
1
SChapter 4

SIUCRIPT 11: Levol 4


'-n2
!"ru, a ... ........................................ 193
4-.f'.' SnC-ýie* v:.4 's ............................. 1ý3
4- : , :. .... .......................................... 196
,4-2.' 7e, ,' •-- '. '~tC. ............................................. 201
4-$4 ?e•,••#n. Ynre. ................................. 2104
i ,-9 . .g,.•- .Azi!' .. ............................... 207

t ~~~~4,7 A!!2t.Iý 6 ':--z#t4 1


4-2.• A• CriŽ'esw .W'a.•;.f - --..................... 222
4- '• k'. •n 3e#;: >ie'.r zr'1--. "P ,t o............ 223
4-•:. .r : • : e. s .............................. 236
-:: 'o., .................................. 242
t.:2 : . "," I : .. ,a-r:?ts .................................. 244
4-13 . , " .•- r -e .. : ................................ 246
-xi-

4-15 Deletion of Set Routines ............... 257


* 4-16 Left-Handed Functions ... .................. . 259
* 4-17 Monitored Attributes and Variable. ................. 262
* 4-18 Subprogra--A New Variable Type .................... 267
4.19 TEXT--A New Mode .................................. 272
4-20 Assignment Without Conversion ...................... 279

Chapter 5
SIMSCRIPT I: Level 5 ............................. ....... 281
5-00 Introducticn ....................................... 281
5-01 Decribing System Dyncrics ........................ 282
5-02 Controlling System Dynamics ........................ 293
5-03 Modeling Statistical Phenomena ..................... 312
5-04 Model Debugging and Analysis ....................... 322
5-05 A Simulation Exmple ................ ... ............ 336
5-06 Miscellaneous Simulation Topics .................... 357
5-07 Reocap .............................................. 366

Appendix ......... ........... .. ... *. ..... *..* ........... oa 369

Index . ...................................................... q. 371


-1-

Chapter 1

SIMSCRIPT II: LEVEL 1

i-00 INTRODUCTION

A conmputer program is a list of instructions that direct a com-


puter to perform certain tasks. A computer language is a special set
of symbols that a programmer uses to write programs. A SIMSCRIPT II
program is a computer program written in the SIMSCRIPT II programming
language. Here is a simple example of a SIMSCRIPT II program:

READ X, Y AND Z
ADD X + Y TO Z
PRINT I LINE WITH Z AS FOLLOWS
X+ Y+ z =
STOP

This program consists of four SIMSCRIPT II statements. The statements


are instructions to (1) read the values of three variables called X,
Y, and Z from punched cards, (2) add these variables together, (3)
print the sum of the variables, along with the label X + Y + Z -, and
(4) stop. They illustrate the basic computer operations of input
(reading data), computation, and output (printing results).

1-01 VARIABLES

As shown in the above example, programs use names as identifiers


to refer to values of program variables. A program statement such as
ADD X TO Y means ADD the value of X TO the value of Y. Since computer
programs often require more than 26 variables (tie letters A through
Z), SIMSCRIPT II uses combinations of letters and digits for variable
names.
-2-

A nz'ne is any combination of letters and digits - A through Z


and 0 through 9 - that contains at leant one letter. For example,
X, COST, COSTOFX, SIZE, MAN3, PARTI, ACCOUNTSRECEIVABLE, 5Y, and 1A
are all legal news, whereas 27, 1, and 4.6 are not.
Variable "mes refer to numbers that are stored internally in
the computer; variable values may be whole numbers (integers) or num-
bors with a fractional part (decimal numbers). The value of a variable
X may be 0 or 125 or 16.72 or -0.00001 or whatever number we assign
to it. From here on, whenever a variable name is used, it is with the
understanding that it refers to the value of a variable (a number
stored in tha computer) and not to the name itself.
At the start of prosran execution, all variable values are set
equal to zero. These variables are said to be "initialized to zero."

1-02 CONSTANTS

Frogram statements often use numbers directly, such as the "2" in


ADD 2 TO SUM, or the number "3.14" in SUBTRACT 3.14 FROM VOLUME. These
numbers are called oonstants When used, they refer to their literal
values; they do not represent other values,
Constants my take t.n the same numerical values as variables, and
may be used interchangeably with them in all computations. Constants
differ from variables in that their values cannot be changed. ADD 5
TO 4 is not a legal use of the constant 4. because it is tantamount to
trying to change the value of 4 to 9; ADD 5 TO X is a legal use of the
variable X and the constant 5.
Whole nubers and fractional numbers, signed or unsigned, are
allowed as constants. Where equivalent representations of a number
exist, they have the arne value; 2.5, +2.5. and 002.500 all -resent
-

the ue number. The statements ADO -1 TO COUNTER. ADO -1.00 TO


COUNTER. and SUBTRACT 1 FROM COUNTER all have the same effect.

1-03 ARrTWA'IC EXPRESSIONS

Arithmetic ex.zpesione arm formed by combining variables and con-


stants with arithmetic operators. The arithmetic operators are:
-3-

+ (add), - (subtract), * (multiply), / (divide), and ** (exponentiate).


Two of these operators. + and -, can be used as unary operators,
that is, with a single variable or constant. The constants +1 and
-1 are examles of the use of + and - ab unary operators on the con-
stant 1. All of the operators can be used as binary operators, that
is, with two variables (or constants, or a variable and constant).
If ye let A and B represent either a variable or a constant, then:

(1) + A and - A are uses of + and - as unary operators.


(2) A * B, 4 * B, A / B, A ** B are examples of arithmetic
expressions that use binary operators.

The simplest expression consists of a single constant, or a single


variable, perhaps preceded by a unary + or - operator. An expression,
+A, may be written as A, wi~h the unary plus implied. This is not
possible, of course, with the unary minus operator.
All operators mist be explicitly expressed, and no two operators
can appear consecutively. For example, multiplication of the variables
A and B must be written as A * B. and not AB. The latter -iould be
interpreted as the valua of a variable called AB. Addition of the
expressions A and -B can be written as A + (-B) or A - B. but not
A + -B.
This last example shows that parentheses must be used to separate
unary and binary operators. Parentheses may also be used (1) to clarify
the operations in an expression so as to make it more readable, or (2)
specify the order in which the operations in an expression are to be
performed. Simple ex'presseions can be connected by any of the arithmetic
operators (+, -0 *. /0 *&) to form compowid .xproasio.S. The "paren-
theses rule" states that expressions are evaluated from left to ripht.
removing parentheses before applying operator hlerarchy rules. Imbedded
parentheses are evaluated from the inside out. Thus:

(1) a + (b'c) + d is evaluated by first computing (bec) as


the value of an intermediate expression e. and then by
evaluating the expression a + • + d.
(2) a + (b/(c + (d&e))) is evaluated by first computing
x - (de). then y (c + x). then x - (0/0). then
(
a + 5.
-4-

Where parentheses are omitted, the hierarchy of operations is:

a. Exponentiation
b. Multiplication and division * and /
c. Addition and subtraction + and -

This hierarchy specifies the order in vh•ch the different operations


are performed relative to one ancther. Exponentiation ts performed
before multiplication or division, and either of these before addition
or subtraction. For example, the expression A+B/C+D**E*F-G is taken
to mean A + (B/C) + (DE * F) - G. If precedence is not completely
specified by these rules, the operator farthest to the left in the
expression is performed first, as in A*B/C, which is computed as
(A * B) I C.
An expression is vritten as a string of variable names, constants,
aritlmetic operators, and parentheses. Any number of spaces from zero
upvard may be used to separate the parts of an expression, A+B, A+ B,
A + B and A +5 being treated identically. The exponentiation opera-
tor, **, Js treated as a single unit and no spaces may appear between
its tvo asterisks. Some example expressions are:

(1) PRICE a variable is itself an expression


(2) (PRICE) parentheses are optional
(3) DUEIN-DUEOUT
(4) PRICE * QUANTITY
(5) PRICE * (ORDER-SALE) parentheses change precedence order
(6) 53 a constant is an expression
(7) A+ 8 + C+ D
(8) X ** 2 in mathematical notation this i X2

(9) A + X 2 + X eL 4 (9) and (10) are identical


(10) A + (x 2) + (x - 4)
(11) x + Y/Z
(12) (X + Y) IZ this is not the sm as (11)
(13) -AB --me&no - (A)
-5-

1-04 LOGICAL EXPRESSIONS

Arithmetic expressions can be used vicl reatina'•a 'pematcre to


form logical ezpweasione that are either true or false. A logical
expression is formed by joining two arithmetic expressions with a
binary relational operator. The relational operators are:

equal
÷ not equal
< less than
< less than or equal
> greater than
> greater than or equal

When a logical expression is encountered during the execution of


a program, current values of the variables in its arithmetic expres-
sions are used to determine its truth or falsity. Thus, if X - 1 and
Y - 0, the logical expression:

X - Y is false
X> Y is true
X< Y is false
X+ Y - X * Y is false

For readability in different contexts, SIMSCRIPT II provides


alternate ways of writing logical expressions. Table 1-1 relates the
mathematical symbol of each relational operator with keypunch symbols.
English abbreviations, and "literary English" equivalents permitted
in SIMSCI.IPT II comparisons.
Unless the keypunch syabois (coltmn 2) are used. each relational
operator must be separated from the arithmetic expressiors on either
side by a parenthesis, or at least one blank colmn.
Typical logical expressions are:

a. Y 0
b. AGE LESS THAN RETIREMENT
c. CODE NOT EQUAL TO ZIP
d. LEVEL LT THRESHOLD
e. (FIXED * *JER " UNITS) GREATER THAN L0ID
f. A G1 (8 # X 2 * 3.57/C)
g. (X 2 + Y 2) GREATER THAN *'Z
h. X 2 + Y 2 1 Z "" 2
-6-

Table 1-1

RELATIONAL OPERATORS

Permitted Permitted
Hathemacical Keypunch English "Literary English"
Symbol Symbol Abbreviation Equivalent

- EQ EQUAL TO
EQUALS
"NE NOT EQUAL TO
< LS LESS THAN
LT
GR GREATER THAN
GT
< < LE NO GREATER THAN
NOT GREATER THAN
G> NO LESS THAN
-_ _NOT LESS THAN

Examples a and f demonstrate that arithmetic expressions say be


enclosed in parentheses vithout changing their meaning. Examples g and
h illustrate the use of equivalent form of a relational operutor.

2-05 READING DATA F"(W PC WIED CARDS

Specific numrical values can be asigned to program variables


by reading nubers (data) from punched cards. An exmple of the READ
statement that doe this is:

READ X. Y AND QUANTITY

I. Y. and QUANTITY are variable nas. They are used in this state-
ment in a LvmiablZ %.ww list.
ia general a SISCRIPT II 4'it consisto of a string of quantities
separated by either a co, or the vord AND. or a coma followed by
the word AAD. Sesi examples of lists &a they sight appear in READ
etatats are:

READ PRICE, QUANTITY. DISCOUNT


READ PLACE A DISTANCE
READ UK. DATE, PLACE AND TIE
READ XW. ANO DATE. PLACE AND TIME
-7-

The general form of a READ statement is

READ riabte n•'w Zlist

When a READ statement is executed in a SINSCRIPT 1I program, as many


numbers are read from data cards as there are variable names listed
in the statement. Successive numerical values are read and "signed
to corresponding variables in the READ list. The ntmbers Can be punched
in the cards in integer or decimal form; e.g., the punched nubers 5,
5.0, and 5.000 are equivalent. Numbers must be separated from one
another by at least one blank column. A ntmber is also terminated at
the end of a card.
Successive READ statements do not necessarily read new data cards.
as SISCUPT II program treat input data as a continuous stream of
ntmbers. The location of a number on a card is not considered. The
folloving example illuitrates this "free form" concept.

READ X, Y, Z sets X - 3, Y - 2.1 and Z - 67.33 when each of


these data card sets is read:
(1) card 1 3.0 2.1 67.33
(2) card 1 3.00
card 2 2.1 67.33
(3) card 1 3
card 2 2.1
card 3 67.33

A READ stateent is often the first statement encountered in a


program. since it is typically used for assigning initial values to
program variables. It is also used for reading in new values during
the course of computation.

1-06 SKIPPING UMwAMrzD DA)Ar

Data cards often contain more information than we vent to use in


a program, as, for example, when prepunched cards are obtained from
somee else.

The megnitude of a number is considered, however, since a digital


amsputer can only store nimberv that lie vithin a laiited range ad
"that hide a limited precision. V.mbers that exceed these limits cause
SIP6CRIFT II prog:eme to stop vhen an attempt is made to read theo.
Thase limits vary vith the computer employed.
-8-

The SKIP statement simplifies the task of skipping unwanted data.


A statement of the form

SKIP e FIELDS

passes over e data fields. The arithmetic expression e is rPowded


to an integer if necessary. If it is negative it is treated as an
error, causing the program to terminate. For example4

SKIP 2 FIELDS
skips the next two data fields, and

SKIP I/J FIELDS


skips no data fields if I/J is equal to 0, skips 3 fields if I/J-
2.7, or 4 fields if I/J - 4.13.

When a data field (value) is read, the SIMSCRIPT II system waits


at the end of the data field in preparation for the next READ state-
ment. Hence, when a field at the end of a data card is read, the
card is retained until the next READ statement is executed.
The SKIP statement can also be used to skip -ie remainder of a
current data card when it is written as

SKIP 1 CARD
An equivalent statement

START NEW CARD or START NEW INPUT÷' CARD

is smewhat more descriptive.


The SKIP card statement can be generalized to the form

SKIP e CARDS or SKIP e INPUT CARDS

in which case the current Jata card and the following e - 1 cards are
bypassed. If the expression (e) in zero, no cards are skipped; if it
is negative, the program terminates with an error message. Example:

Data fields are contiguous strings of characters separated by


at least one blank.
The word INPUT is optional. If not u&ed It Is imlied.
-9-

SKIP 3 CARDS

ejects the current data card and skips over the next two data cards.

1-07 COMPWUTING VARIABLE VALUES

One way of assigning a value to a variable is to use a READ state-


sent. A second way is to use a LET statemen:. The general form of
this statement is:

LET Ar,•able - arithmetic expvaeion

as in the statements

LET X- 0
LET X - (Y + 1)/15
LET PRICE - QUANTITY * SALESPRICE
LET BALANCE - STOCK - PURCHASE
LET UNITCOST = TOTALCOST/NUMBEROFUNITS
LET E - I*R

When a LET statement is executed, the current values of the


variables on the right of the equals symbol (-) are used to compute
the value of thm arithmetic expression, and then this value is assigned
to the variable on the left of the equals symbol.
Used this way, the tquals symbol is not r relational, but an
aseigniet operatcr. rhe statement LET X - Z + 1 sa&s nothing about
the equality of the vartable X and the expreesion Z + 1. It evpresses
a command to evaluate Z + I and assign this quantity as the new value
of X. In the statement

LET X - Y*2

the value of th expression Y? is coaputed and arsi.•ied to the vari-


I able X.The previous v,ýlue of X is replAced b'y the niiw value; and in

LET X - X + l

a new valut of I is computed by adding I to the current value of X


and assigning this nav value to I.

The ADO and SUSTTRoACT stateents are used to &Ad or su!.tract t-he
-10-

value of an arithmetic expression to or from a program variable.


Their action in like that of the LET statement, the difference being
that an arithmetic operator is incorporated in the statements them-
selves. The statement forms are:

ADO arithmetio ezpression TO uariabLe


SUBTRACT aroitwtic ezpression FROM uai'able

The statements are equivalent to the LET statements:

LET 'ariab:e- variableu + ariowtic expreeion


LET vriable - thzriable - w'-it~u'wti'c expes~iij
The ADO and SIJBTRACT statements have the virtue of being easy to vrite
and straightforward in meaning. Some examples of these statements &re:

ADO 1 TO COUNTER
ADO IT7LCOST TO BILL
SUBTRACT 3*X + 6*Y FROM Z
SUBTRACT COST 9ROM CASH

1-09 A PRO&WM ON CARDS AND THE PLOW OF COWPVTA2'ro

SIMSCIIfl I progrm are compoeed of sequences of conventionally


arranged symbols, som of which are standardized key words such as LET
and W(AD, others of which are programmtr-constructed variable names
and numerical conatantd. The basic symbolic units that the SI1SCRI7T
It compiler recognizes in scanning program statements are r.ies antl
numbers, tho special characters +. -. *. /1 9,(V), o a, .
to ?, it :1 ;, %,-1, it s. 0, 00 " . and the punctuatiott marks
period, comma. and blank. Sections i-01 and -112 described ho naines
and numbers are formed, and Seca. 1•03 and 1-04 illustrated the ue*
)f emse special characters. Except for vassing mention@, the punc-
tuation marks perioO, coma, and blank have not been discussed.
SIGCRIPT I1 ignoree all periods written at the end of name ani
numter*. While a programmr may wish to use terminal periola tr'
J1s*lty or dross w a program, they are etripped from all names and
rmbere during compilation. Thus the na, JACK... is interpreteo as
JACK,. ems the number 5. as 5; the ism" DOT. DOT.. ens DOT.., wmie
looking different, are all treated the eme . %sturallh, this does
sot sply to periods used within numbers. as in 5.6 end 2457.8%.
-11-

Commas are required in some places in SISCRUf I I statements and


optional in others. In particular, they are required between items in
a list of any sort, and optional after the logical condition of an IF
statement. Whenever a comr may o0 most be used in a particular
statement, its use is made clear in the section of the text that de-
fines the statement.
Since SINCU•C•1 ! statements are not written in any specific
format, but spaLed across and between punched cards as a programmer
wishes, blanks ere needed to separate words (names, numbers, and key
words) in statemerts. Tvo adjacent statement words must always be
separated by at least one blank unless ore of them is a special char-
acter. Thus, LET X - Y can be written as LET X-' but not as LETX-Y,
and IF (SIGN + 5) IS GREATER THAN DELTA can be written as IF(SIGN+5)
IS GREATER THAN DELTA but not as IF(SIGN+5)ISGREATERTNANDELTA. Merely
looking at a statement usually makes it clear whether a blank is needed
or not. Since uultiple blanks are treated as single blanks, blank
characters can be freely used to improve the readability of statements,
as many of the illustrations in this Report demonstrate.
Statements can be punchei as desired on cards, with one slight
restriction. A statement can be vritten on more than one card, or
several statements can be written on the ame card, but statement
vorde (names. ntmbers, and kuy vorde) cannot be split between cards.
The only effect of this is to restrict names and constants to 80 or
fewer characters. (Remember that the exponentiation symbol "" is a
Ssingle unit and cannot be aplit.)
Normally, computation proceeds from statement to statement in
the order in wthich statements physically appear in a pregram dec'.
For esample, in the four-statement example on r. 1, the program first
executes the READ eoatmnt, then the ADO statement, then the FRINT
statement, and halts v~hon it reaches "he STOP statement.
It is po•esible to altar the otherwise stratghtforwrd floy of
computation by using a statement that directs a progr-m tc transfer

This statement is discussed in Sec. :-.2.


-12-

to a labeled statement (Sec. 1-11), or that specifies alternate pro-


gram paths contingent on the truth of a logical expression (Sec. 1-12).
A statement is labeled by putting a name before it, enclosed in
single quotation marks. This name is called the Zabel of the state-
ment, and reference to the label is understood as reference to the
statement. Thus in the program fragment

'HERE' LET A = 0

GO TO HERE

GO TO THERE

'THERE' LiT A = 0

the specified transfers are to the statements LET A=O.


A l:bel name can be any combination of letters and/or digits.
Some possible label names are:

'READNEXTDATACARD' 'X' '1'


'PARTI' 'SIMSCRIPT' '12345'
'COMPUTE' 'A12345'

1-10 CLARIFYING COMMENTS IN A PROGRAM

Wherever it appears that a clarifying remark would be helpful to


the reader, a comment should be used. A commnent is any string of
characters enclosed in double quotation marks ('') on the left, and
by either double quotation marks (") or the end of a punched card on
the right. Comments can appear anywhere in a program except within
a word; they serve no function other than documentation. We strongly
recommend the liberal use of comments wherever the intent of a program
is not completely clear from its SIMSCRIPT II command description.
Some examples of co.'ments are:
-13-

(a) READ X, Y "INDEPENDENT, DEPENDENT VARIABLES


(b) READ DOLLARS ''CASH FLOW'', EQUITY "PROPERTY VALUE
(c) IF X EQUALS Y, ADD X TO SUM GO TO SUCCESS
OTHERWISE "TAKE REMEDIAL ACTION'' GO TO ERROR
(d) STOP "NORMAL, NON-ERROR STOPPING POINT

1-11 CHANGING THE FLOW OF COMPUTATION BY DIRECT ORDER

If a label has been defined somewhere in a program, the flow of


computation can be directed to the statement named by the label by
using the GO TO statement. This statement is of the form

GO TO 'label' or GO TO label

Quotation marks are mandatory when a label is defined (i.e., when it


appears in front of a referenced statement) but optional when used in
a GO TO statement. The word TO is also optional. The ability to
direct the flow of control within a computer program is often conve-
nient and frequently essential. A simple example of a GO TO, based
on the program of p. 1, reads a set of data cards instead of only
one card:

'READ' READ X, Y, Z
ADD X + Y TO Z
PRINT 1 LINE CONTAINING Z AS FOLLOWS
X + Y + Z =
GO TO READ
The program returns to the statement labeled 'READ' after it has
finished printing, and continues to do so until all the data cards
are read, since an attempt to READ a card when there are no data auto-
matically terminates a program.1

1-12 CHANGING THE FLOW OF COMPUTATION BY LOGICAL EXPRESSIONS

Additional power to transfer, namely "branching capability," is


incorporated in a statement that enables a programmer to alter the
flow of computation based on the current value of a logical expres-
sion. The IF statement tests the truth or falsity of a logical expres-
sion and branches (transfers) accordingly. The general form of the

t S
See ec.-10 proramtermnaton
o en-of-ile
-14-

IF statement is

I F Zogical expreeeion group of statements REGARDLESS

as in

IF NUMBER N**2 LET FLAG - 0 ADD NUMBER TO SUM REGARDLESS LET A 55

If the logical expression is true, the statements between the logical


expression and the word REGARDLESS are executed, and then control is
passed to the statements following the word REGARDLESS. Of course,
a GO TO statement can be used to direct control to some other point
in the program if this is required. If the logical expression is
falee, the expressions in this group are bypassed by control being
transferred to the statement following the word REGARDLESS. The
words ELSE, ALWAYS, and OTHERWISE may be used as equivalents for
REGARDLESS. Often the different shades of meaning effected by these
words aid in transmitting the intent of a program.
A logical expression of the form expression relational operator
expression can be written as expression IS rotationa! operator expres-
sion. Examples are:
X IS EQUAL TO Y
AGE IS GREATER THAN 27
LIMIT IS NO LESS THAN LOW
SPACE IS NOT EQUAL TO VOLUME
The addition of the word IS improves the readability of IF state-
ments. Some sample uses of IF statements are:
(a) To read a set of 100 numbers and add together those
numbers greater than 5.
'READ' ADD I TO COUNT
IF COUNT > 100 GO TO FINISH
ELSE READ N
IF N IS GREATER THAN 5 ADD N TO SUM
REGARDLESS GO TO READ.
'FINISH' ''CONTINUE PROGRAM"

(b) To read a set of 200 numbers and sum all those numbers
greater than or equal to 5 in one group, and all the
numbers less than 5 in a second group.
-15-

'READ' ADD 1 TO COUNT


IF COUNT > 200 GO TO FINISH
ELSE READ N
IF N IS NO LESS THAN 5 ADD N TO SUMI
GO TO READ
OTHERWISE
ADD N TO SUN2 GO TO READ
'FINISH' "CONTINUE PROGRAM"

(c) To test for an "end of data" signal.


'READ' READ N
IF N EQUALS 0 GO TO FINISH
OTHERWISE ADD N TO SUM
GO TO READ
'FINISH' PRINT I LINE WITH SUM AS FOLLOWS
***.** IS THE VALUE OF THE SUM.
STOP

(d) A data processing teat.


IF SUM IS LESS THAN SUMTOTAL
IF X IS GREATER THAN HI SO TO H
ELSE IF X IS LESS THAN LO GO TO L
OTHERWISE
OTHERWISE
ADD X TO SUM
This program is represented in flow chart form as:

Start SUM<SMTOTAL X >H GO TO

Faalse
Fl

X<LO GO TO L

ADD X TO SUM
-16-

As shown, IF statements can be "nested" by putting IF statements within


statement groups of other IF statements. When this is done, a simple
indenting and alignment of statements is advised to make the flow of
control clear. The following program illustrates this; notice how
each IF is aligned in a card column with the OTHERWISE (or ELSE or
ALWAYS or REGARDLESS) that matches it.

IF X IS LESS THAN A
IF Y IS LESS THAN B
LET Z - A + B
REGARDLESS
GO TO 'Al'
OTHERWISE
GO TO 'A2'

X<A
Star YesY<B es =A+B

Gramatically, the IF statement often seems to ask for a comma


as in: IF X - Y, GO TO 'READ' or IF AGE EXCEEDS LIMIT, STOP. For
this reason, an optional comma is permitted in the IF statement after
the logical expreiaion.
The true branch of the IF statement, i.e., the statement group
executed if the comparison is true, can contain any number of STMSCRIPT
II statements. The only qualification on this group is that it must
be self-contained with respect to other IF statements that appear
vithin it, since each IF is matched with a corresponding OTHERWISE,
as left parentheses are matched with right parentheses in an exnres-
sion. An unmatched, or out-of-place OTHERWISE can change the meaning
of a prograi. In tne above examples containing nested IF statements,
note that each IF has a matching OTHERWISE.
-17-

1-13 DISPLAYING THE RESULTS OF COMPUTATION

The PRINT statement has been used in several examples to display


titles and labeled computational results. This statement has two
major forms, either

PRINT i LINES AS FOLLOWS

or
PRINT i LINES WITH arithmetic expression Zist AS FOLLOWS

followed by i lines of descriptive text and format information. The


line count i is, of course, a positive integer constant. If i 1
the word LINE can be used instead of LINES. Equivalents for the AS
FOLLOWS portion of the statement are THUS, and LIKE THIS. Sample
PRINT statements are:

PRINT 2 LINES AS FOLLOWS


PRINT 1 LINE THUS
PRINT 2 LINES WITH X AND Y LIKE THIS
PRINT 4 LINES WITH X, X**2, Y, Y**2, X*Y, N AS FOLLOWS

The i lines, called format lines, that follow the PRINT state-
ment can contain as many as 80 columns of textual infor-nation and
formats for arithmetic expressions whose values are to be printed.
There can be either text, or formats, or both in any format line.
The length of a format line is measured as the number of columns from
column 1 to the last nonblank column in the line.
Textual information appearing in format lines is printed exactly
as it appears; thus, the statement

PRINT 1 LINE AS FOLLOWS


...... THIS IS A SAMPLE FORMAT LINE ......

prints a single Line of output containing the above message. The


statement,

PRINT 2 LINES THUS


SUMMARY REPORT
INCOME DATA EXPENSE DATA
-18-

prints two lines of output as they appear on the format cards. Any
character except an asterisk (*) or a parallel (I) can appear in a
format card as a textual message; blanks are "printed" as empty columns.
When PRINT statements are used to display the value of arithmetic
expressions, the expressions are listed in the PRINT statement, and
descriptive formats are provided for their values. The expressions
are first evaluated, and then printed in the display formats in left-
to-right order. The statement

PRINT I LINE WITH X, Y, X/Y, N**2 AS FOLLOWS


X a * *, Y *** X/Y - **.'*, N SQUARED ***

evaluates the expressions X, Y, X/Y and N**2 and displays their values
according to the format rules shown in Table 1-2.
The variables PRICE and ITEMS appearing in the folloving PRINT
statements are assumed to have the values 100.899 and 27, respectively.
(a) PRINT 1 LINE WITH PRICE/ITEMS THUS
PRICE/ITEM -

is printed as

PRICE/ITEM - $3.737

(b) PRINT 1 LINE WITH PRICE/ITEMS AS FOLLOWS


PRICE/ITEM- 5*.*"

is printed as
PRICE/ITEM - $3.74

(c) PRINT 3 LINES WITH PRICE, ITEMSPRICE/ITEMS THUS


PRICE - 5"**.*
ITEMS -
PRICE/ITEM - 5".*"

is printed as
PRICE - $100.9
ITEMS - 27
PRICE/ITEM - 53.737

When several values are to be printed contiguously, the single


parallel (1) is used In place of am asterisk to terminate a format on
the left. If this is not done, tvo contiguoue formats merge into m
another. Thus two contiauous t1hree-digit integer fields can be
-19-

Table 1-2
FODEAT COWMfIOIP USED 1N P IDE STATDENOT

1... "rLestfmern "Lay lqbis haspie.

Zaseui (a)Pulg M Laetsg valooesM P IN1 LINE WIrH J THM

"low,~ Wetli a toweai Letapr putse. *be J33


voe-yso. o . oa TW VALUE OF jIs 3
get"e of cm ~tamrsee depend-
Log o t sign.l MW tuaseting of Prieato. byt 39.7
as eimsol; 1E VALUE OF J is 10
(a) petat as o digit as poesalbs o rs eJ 9.
spesuamtlve & or teawL .bat.- Mi V~IEU OF J IS48
Ct * treatis Sb. utafwost as
the lo order paaIt~eal it set
asfftleii qsosa. swa astoolift.

(4) .sy the posaitiveof A rtakt-


woot digit meat be dwf.

~l *@ (a) priac a daslamit 96a641 PNT 1 LINE WITH I TWAS


so* (b) treat tale apto part as (a) WVIUOFIi
* am (40 sheys Pciate fte Ita

*.a* (a) road the dealmal part to tbs lE VALUE OF I Is 3.25


inwbo of digits qmIfted 4 11 1 - 3.95 tb. oewrowsiss
&a.** ~astartabas to lbA itjot of lb. eprs~Sis3 AS .0
isalami potat; as MovesLo to 0r 3.354l.ag Ike Velma5 o.f
mdvade to t~be Ml deAlMI place 1. as stared i the ~swe~a
.
by &&Meg 0.5*010"(-0) O- trfc to otbfagd. Itlbs
forest
~a ate A"ealvide;
at&& t *.be. 3.5 petate as 3.5w0
(4) it tri-titag deaema! digits a"e

boaftd fiat a coedd Iscapi wdtw 3.23? PetalasGo3. id Mhe

iT~iti .* Pitat a twactlawAd Velma 6000sm W.(?, Pvltet a. .21)'


0 Mad I lbs
tha ist .40

beaufe. (a) Pvti'. a ftembrt as fteem Vluea lb. Khst ....


at lmeas "t. h*S&I anw b lMe Valwa, 3736.21 to patsed
oestive Mb the el.. of dwsnuted a- as3.1003
pe"OOinLa
to &Wm Md I rd Sa
hnt "we.......
616oftalIt woul be prided a.
-20-

expressed as '**I'*, and six contiguous one-digit integer fields as

Ill'11.
Blank lines can be inserted between PRINT statements by the SKIP
statemnt, or blank format lines can be used. if e is any aritnmetic
expression, then the statement

SKIP e OUTPUT LINES

skips a number of linen equal to the value of e rounded to an integer,


as in

SKIP 1 OUTPUT LINE


SKIP N OUTPUT LINES
SKIP X + 3*Y OUTPUT LINES

If e is negative, it is treated as zero. At moast, one complete page


will be skipped.
Pages can be ejected before printing, so that the next PRINT
statement starts at the top of a new oage, by using the statement

START NEW PAGE

The PRINT, SKIP. and START NEW PAGE statements can be used to-
gether to produce attractively labeled output reports.
As a final caution, note that whereas a PRINT statement can appear
on a card with previous stateme-'-, each of its following format lines
must appear on a separate card. This is illustrated in the following
program:

'READ' READ X IF X IS LESS THAN 10. GO TO 'READ'


ELSE PRINT 1 LINE WITH X AS FOLLOWS
THE VALUE OF X IS ***.*"
IF X EQUALS 9999, STOP
OTHERWISE GO TO REAr)

1-14
.•'.' • -, ..4, .; P - ;F.•
"1Y?4 -*. AV

The ST0OP ntateuent ts aued to terainste a pro~rar. Since there


may be many ST')P statements in a program, it n*eA net appear physically
at the end of a progra deck. The following proiasa illustratcs t0e
uee of the STDý' statement in co-junctton with tvv IF stptew-'ts:
'BACK' READ N
IF N EQLALS C, STOP
OTHERWISE ADD N TO SUMOFN
ADD I TO IOTAL
PRINT I LINE WITH S1MOFN/TOTAL LIVE THIS
AVERAGE N SO FAR " *-*.***
IF TOTAL EQUALS I000, STOP
ELSE GO 'BACK'

1-I THK PHŽ.SICA.' END OF A PROC'RAM

The last statement in every SIMSCRIFT II program must be END.


It signals that the entire source program has been read. The example
programs at the end of this section illustrate the use of the END
statement.

1-16 S..W. SAMWLE 57,wgCnIPT ri, YVEZ'T . Ph•.•-Z.4W•

The folloing programs illustrate the SIMSCRIPT .!l concepts and


statements presented in this section. The programs are printed as
they might appear on punched cards before being submitted to a com-
puter for processinji. Since the flexibility of the SINSCRIPT II
progran statement format makes many card layouts possibl-, the formats
used in these examat1s are only some of many possible choices.

.F- .. in-lip," th•e tfx-m ton -.z•...! : ,Yint,--.0.of az e .7et


1 •b-f•
N numbers are o, punched cards. The folloving program reads

these numbers. and determines their minimum and maximum. When all
tht numbers have been processed, N, their average value, and their
winimum and mai-'inun values, are printed.
Notice that since the range of the numbers is unk:no•, t'•e varn-
able PX is initialized tc a large negative namber and MIN tn s large
FpwLtive nuuber to ensurv that tSe largest and saallest data values
arc retsaind.
-22-

"THIS PROGRAM COMPUTES THE AVERAGE AND THE MINIIM AND MAXIMUM OF
"A SET OF NUMBERS ON PUNCHED CARDS
LET HAX- 99999.99999 LET MIN--PAX
READ N " THE NUMBER OF DATA OBSERVATIONS
'R' READ X A'DATA OBSERVATION
ADD X TO SLIM
IF X IS GREATER ThAN MAX. LET MAX-X REGARDLESS
IF X IS LESS THAN MIN, LET MIN-X REGARDLESS
ADD 1 TO COUNTER
IF COUNTER IS LESS THAN N, GO TO R ELSE
START NEW PAGE
PRINT 3 LINES WITH N.SLM/N,MAX.MIN AS FOLLOWS
THE AVERAGE VALUE OF ** NUMBERS IS ..
THE MAXIMUM VALUE IS ' "
THE MINIMUM VALUE IS . . -
STOP END

1-16-2 A Simple Ac•owiti'g System

The folloving program processes sales and inventory receipt


transactiona in a prototype accounting system. Each transaction card
contains a dollar amount, an account code for the debit account, and
an account code for the credit account. A zero dollar amourt signals
the end of tranaactions.
At the statement labeled 'START', the 8 accoimts and 2 totals
are set to their last month's values by roading these values from
punched carde. At the end of the program, updated values of these
10 variables are printed for use in next month's accounting run.
Each transaction is processed through ow debit account; the
sequence of IF statements aft.ar the label DEBIT direct the computation
based on the debit code nuber (CODE]). Note che PRINT statement at
ERR1, which catches a aispunchod debit code, i.e., a code other than
1, 2. 3, 4, or 5. Each traseaction iG siailarly processed through a
credit account.
wheo all the transaction cards have been read, a balance sheet
and the montCly balances are printed. 4ote the different %see of the
PRINT statement: to print titles and headtnts, and to print labeled
variable ve1'.
-23-

" THIS PROGRAM IS A SIMPLE ACCOINTING SYSTEM


'START' READ CASHRECEIVABLESINVENTORYPLANTEQUIPMENf".TOTALASSETSPAYABLES,
LOAN,EQUITY,TOTALLIABILITIES
'READ' READ DOLLARS,CODE1,CODE2
'TEST' IF DOLLARS EQUALS 0, GO TO 'FINISHED'
OTHERWISE ADO 1 TO TRANSACTIONCOUNTER
'DEBIT' IF CC-DE1 EQUALS 1, ADD DOLLARS TO CASH GO TO TOTALD ELSE
IF CJD(1 EQUALS 2, ADO DOLLARS TO RECEIVABLES GO TO TOTALD ELSE
IF CODE1 EQUALS 3, ADO DOLLARS TO INVENTORY GO TO TOTALD ELSE
Iý CODE1 EQUALS 4, ADO DOLLARS TO PLANT GO TO TOTALD ELSE
IF CODE1 EQUALS 5, ADO DOLLARS TO EQUIPMENT GO TO TOTALD ELSE
'ERRI' PRINT 1 LINE WITH TRANSACTIONCOUNTER AND CODE1 AS FOLLOWS
TRANSACTION **** HAD CODE1 PUNCHED AS ***
STOP
'TOTALD' ADO DOLLARS TO TOTALASSETS
'CREDIT' IF CODE2 EQUALS 1, SUBTRACT DOLLARS FROM PAYABLES GO TO TOTALC ELSE
IF CODE2 EQUALS 2, SUBTRACT DOLLARS FROM LOAN GO TO TOTALC ELSE
IF CODE2 EQUALS 3, SUBTRACT DOLLARS FR1nM EQUITY GO TO T OTALC ELSE
'ERR2' PRINT 1 LINE WITH TRANSACTIONCOUNTER AND CODE2 AS FOLLOWS
TRANSACTION *'* HAD CODE2 PUNCHED AS **
STOP
'TOTALC' SUBTRACT DOLLARS FROM TOTALLIABILITIES
GO TO 'READ'
'FINISHED' START NEW PAGE PRINT 1 LINE WITH TRANSACTIONCOUNTER THUS
***** TRANSACTIONS WFRE PROCESSED THIS MONTH
SKIP 5 OUTPUT LINES
PRINT 9 LINES CONTAINING CASHPAYABLES,RECEIVABLESLOAN,INVENTORY,
PLANTEQUITY ,EQUIPNENTTOTALASSETS
AND TOTALLIABILIT!ES AS FOLLOWS
ASSETS LIABILITIES
CURRENT ASSETS CURRENT LIABILITIES
CASH ACCOUNTS PAYABLE $e*
RECEIVABLES A**** LOAN
INVENTORY *****
FIXED ASSETS EQUITY
PLANT EQUITY $'"
EQUIPMENT
TOTAL ASSETS $"*' TOTAL LIABILITIES $"
SKIP 3 OUTPUT LINES
PRINT 2 LINES WITH CASH,RECEIVABLES,INVENTORY,PL ANT.EQUIPMFNT.
TOTALASSETS,PAYABLES.LOAN ,EQUITY AND
TOTALLIABILITIES AS FOLLOWS

STOP END

Mhe number - 7 .14159


. recurs cometantly in entineertna end

I
7
scientific co •tattons. The follor.wi preXrau use* am "Irnfnite,

I
-24-

series" representation of n to compute its value to four-decimal-place


accuracy. The specific formula used Is

I i 1 111
3 5 7 9* *
The program starts by initializing the variables SIGN and DIVISOR
to their starting value of 1. The variable PI is automatically initia-
lized to 0 at the start of the program.
At the label TERM the value of the next term (1/DIVISOR) is com-
puted. At the label TEST, a test is made to determine if enough terms
have been computed to give sufficient accuracy, using the fact that
any term with value less than 0.00025 will add, or subtract, less than
0.001 to, or from, the sum of the series when it is multiplied by 4
to evaluate 7r.
If the term is greater than or equal to 0.00025, the sign of the
term, which alternates between +1 and -1, is computed and the value
of the term is added to the variable PI. The program then returns to
the label TERM to continue the summation of the series.
When the term is less than 0.00025, the program transfers to the
label FINISHED, where the expression PI*4 is printed.

"THIS PROGRAM COMPUTES THE VALUE OF PI TO AN ACCURACY OF 0.001


'INITIALIZATION' LET SIGN-1 LET DIVISOR=1
'TERM' LET TERM=1/DIVISOR
'TEST' IF TERM IS LESS THAN O.00025,PRINT 1 LINE WITH PI*4 LIKE THIS
THE VALUE OF PI IS *.*****
STOP
OTHERWISE ADD SIGN*TERM TO PI
LET SIGN--SIGN
ADD 2 TO DIVISOR
GO TO 'TERM'
END

1-16-4 Computing the Square Root of a Number

The square root of a number is a commonly needed value. A higher


level of SIMSCRIPT II provides a facility for automatically computing
square roots, but the following program ignores the facility and uses
a mathematical formula to evaluate the square root of a number to a
specified accuracy. The formula is an iterative one, with each
-25-

succeeding value of the approximation to the square root generating


a better approximation. The iterative formula is
1 (x N+
i+1 2 i x

where i is the number of the iteration and xi is the approximation to


the square root of N.
The program is designed to be executed repeatedly for several
values of N. It starts by printing a title for the table of square
roots it is going to generate. At the label READ, the values of N
and the required accuracy EPSILON are read from punched cards, and a
test is made to see if this N, with a value of 0, is a signal that
there are no more data cards.
If N is greater than 0, a first guess at the square root of N is
made at the label GUESS. This guess sets xi, here called SQRT1, equal
to N/2. The iteration starts at the statement label 'LOOP', where
x1+1 2=
1 (xi + N/xi) is
. computed; x++1 is called SQRT.
If DELTA, the difference between SQRTI and SQRT, is less than
EPSILON, the required accuracy has been achieved. The values of N
SQRT and EPSILON are then printed and control is transferred to 'READ'
to get a new data card.
As long as DELTA remains greater than or equal to EPSILON, another
iteration is required. For this, xi is set equal to xi+1 (SQRT1 ÷
SQRT), and control returned to 'LOOP'.
A second program computes a square root in the same way, but uses
a different procedure for obtaining successive values of N. This
pzogram illustrates the use of an iteration sequence, a series of
numbers that are equally spaced between two values, to control the
computation section of the program. This important concept is elab-
orated in Level 2.
-26-

" THIS PROGRAM COMPUTES THE SQUARE ROOT OF N TO AN ACCURACY OF EPSILON


" N IS A POSITIVE NUMBER, EPSILON IS GREATER THAN 0 AND LESS THAN 0.00001
PRINT 1 LINE AS FOLLOWS
N SQUARE ROOT OF N EPSILON
'READ' READ NEPSILON
IF N EQUALS 0, STOP OTHERWISE
LET SQRTI=N/2
'LOOP' LET SQRT-(SQRT1 + N/SQRT1)/2
LET DELTA=SQRTI-SQRT
" USE THE ABSOLUTE (+) VPWUE OF DELTA IN THE TEST
IF DELTA IS LESS THAN ',LE) DELTA=-DELTA
REGARDLESS IF DELTA AS LESS THAN EPSILON,
GO TO 'PRINT'
OTHERWISE LET SQRT1=SQRT
GO TO 'LOOP'
'PRINT' PRINT I LINE WITH*** N*SQRT,EPSILON
****
AS FOLLOWS
* •I****

GO TO 'READ'
END

" THIS PROGRAM COMPUTES THE SQUARE ROOT OF N TO AN ACCURACY OF EPSILON


'' THE DATA IS NOW IN THE FORM OF A LOWER AND UPPER VALUE OF N AND AN
" INCREMENT BY WHICH THE LOWER VALUE IS ADVANCED TO THE UPPER VALUE.
" THE VALUE OF EPSILON IS CONSTANT FOR ALL VALUES OF N
READ NNINCREMENT,NLASTEPSILON
PRINT 1 LINE CONTAINING EPSILON AS FOLLOWS
N SQUARE ROOT OF N ACCURACY=*.****
'NEXTN' LET SQRT1=N/2
'LOOP' LET SQRT-(SQRT1 + N/SQRTI)/2
LET DELTA=SQRT1-SQRT
" USE THE ABSOLUTE (+) VALUE OF DELTA IN THE TEST
IF DELTA IS LESS THAN 0, LET DELTA=-DELTA
REGARDLESS IF DELTA IS LESS THAN EPSILON, GO TO 'PRINT'
OTHERWISE LET SQRT1=SQRT GO TO 'LOOP'
'PRINT' PRINT 1 LINE WITH N AND SQRT LIKE THIS
**'#t ** *it***

IF N EQUALS NLAST, STOP


OTHERWISE ADD NINCREMENT TO N GO TO 'NEXTN'
END

1-16-5 A Program for Regression Analysis

Computer programs are often used to analyze data by statistical


techniques such as regression analysis. The following program deter--
mines the coefficients a0 and a1 of the regression equation

Yi " 'So + al1x i

t y1 a
-27-

using the formulae

Nx
N!i N N
iyi" ! x il Yl
a'I N 2 N
N ix x-
i-li i-i 1

N N
I Iyi aliii xi
ao
= N

where

N is the number of observations of x and y,

N
ijxi represents the sum of all the xi
i-i

N 2
x represents the sum of all the x2

etc.

" THIS PROGRAM COMPUTES THE COEFFICIENTS OF THE REGRESSION EQUATION


" Y=AO + Al*X . OBSERVATIONS OF X AND Y ARE ON PUNCHED CARDS
'OBS' READ N
'READ' READ X,Y
ADD X TO SUMX
ADD X**2 TO SUMXX
ADD Y TO SUMY
ADD Y**2 TO SUMYY
ADD X*Y TO SUMXY
ADD I TO NUMBEROFOBSERVATIONS
'TEST' IF NUMBEROFOBSERVATIONS IS LESS THAN N, GO TO 'READ'
OTHERWISE
LET Al-(N*SUMXY-SUMX*SUMY)/(N*SLUMXX-SUMX**2)
LET AO=(SUMY-Al*SUMX)/N
PRINT I LINE WITH AO AND Al AS FOLLOWS
THE REGRESSION EQUATION IS Y=***.*** + . X
STOP END
-28-

Chapter 2

SIMSCRIPT II: LEVEL 2

2-00 VARIABLE AND LABEL NAMES REVISITED

Chapter 1 defines variable and label names separately; a variable


is any combination of letters and digits that contains at least one
letter, and a label is any combination of letters and digits without
the "at least one letter" constraint. Another way of stating this is
to define a name as a combination of letters and digits and an integer
as a combination of digits, and allow a variabZe name to look like a
name and a labeZ like a name or an integer. It is easy to expand
these rules slightly to permit more readable programs by incorporating
periods into the definitions of names and labels.
Let a nam be any combination of letters, digits, and periods that
contains at least one letter or two or more nonterminal periods. Let
a constcnt be any combination of digits, possibly containing one
period. Then a variable name must look like a name and a label can
look like a name or a constant. This allows variables to be dis-
tinguished from numbers while maintaining the widest latitude in
name formation.
Some examples of possible variable and label names are:

Variable names Label names

PART.NUMBER LABEL
NUMBER.OF.PARTS SECTION.1
TOTAL .... I
SECTION ..... 1 12345
.PAGE 12.345
3.7.6 PART.4
. 6 ERROR
-29-

While the fact has already been mentioned, it cannot hurt to


emphasize once more that terminal periods cannot be used in forming
names. The names X, X.., and X.... all represent the same variable
value; the labels '5' and '5.' are identical.
While SIMSCRIPT II does not prohibit the use of any particular
words or names, it does define a number of special words that it
recognizes in certain contexts. A SIMSCRIPT II programer can guard
against using any of these names incorrectly by remembering them or
the special naming conventions used for them. Each of these names
either begins with a le'ter followed by a period (as in the name L.27)
or ends with a period followed by a letter (as in the name SQRT.F).
A programmer can regard these rules as defining prohibited word-forms
or as guides that say, "Check with the Appendix whenever you want to
use a name of this form."

2-01 VARIABLE MODES

So far no explicit restrictions have been placed on the magnitude


or precision of the numbers represented by variable names. Complete
freedom from concern over the expression of numerical quantities can
be a good thing; however, programs can eften be more efficiently
written if a programmer places some restrictions on the type of num-
bers a program deals with.
A variable definition statement is a declarative message from a
programmer to the SIMSCRIPT II compiler. Definition statements declare
that variables have certain properties; the compiler uses this infor-
mation to generate efficient codes.

t The one exception is the word AND, which should not be used
as
a name.
±%fhese words are listed in the Appendix.
t
tParticular implementations of SIMSCRIPT II on different com-
puters will of necessity impose restrict~ons due to characteristics
of the computer hardware used in the implementation. Thus you might
be able to express some numbers (very large or very small) on some
computers, but not on others. These limitations are seen by a pro-
grammer in the magnitude and precision of the numbers he can express,
and in the results of his computations.
-30-f

SINSCRIfl II variables can be declared as INTEGER or REAL. Vari-


ables declared as INTEGER represent whole numbers; variables declared
an REAL represent numbers that can have fractional values. The numbers
56, -6745, 91, -1, and 0 are INTEGER valued; the numbers 56.0, 35.7846.
0.999876, -27.45, and 0.0 are REAL valued. Note that a whole number
such as 56 can be expressed either as INTEGER or REAL. It is the pos-
sibility of a fractional value, and not any particular value, that
makes a variable require a RTAL definition.
Every SINSCRIPT Il program has a preamble that contains variable
definition information. Often this preamble is not written, but im-
plied, as in Level i, where all variables are treated as REAL. When-
ever a variable has a prop-rtcy that diZIers from one that SIMSCRIPT II
assumes, a definition :tatement mast be used. Programs containing a
preamble must begin with the one-word statement PREAMBLE. Following
variable definition statementa must be marked off from succeecing
progrla staterments by the word END. (Sec examples in Sec. 2-04.)
As stated, the mode of a variable (whether it is INTEGER or REAL)
is 3ssumed REAL unless otherwise specified; the "normal form" of
SIMSCRIPT II variables is decimal numbers.
The assumed REAL condition can be changed by using the statement

NORMALLY, MODE IS INTEGER


This statement resets the compiler's "background conditions" so that
all following program variables are assumed INTEGER unless otherwise
sperified. The com., after the word NORMALLY is optional; the word
IS can 'iereplaced by tha equals symbol (a). Thus, the abcze state-
sent can be written as

NORMALLY MC3E IS INTEGER or


NORMALLY NODE - INTEGER

Individual variables that ditfe:, frow the lmpl~ed or NORMALLY


defined mode can have their mode qpecifted in d DEFINE statement.
This statemen' lists one or m•re variable aames and defines their
common mode. The statement

DEFINE X, Y. Z. PAPTNER.ONE AND Wf AS INTEGER VARIABLES


-31-

illustrates the way In which the DEFINE statement is used to declare


z.Aat the five variables X, Y, Z, PARTNER.ONE, and ME are all INTEGER
valued. If the background conditions were INTEGER, the word REAL
could be used to define the variables as REAL.
Ths DEFINE statnment has a number of alternative form; the only
words that must appear in it 4re DEFINE, the variabi.e names being
defined, AS, and the word VARIABLE or VARIABLES. The wo-As A, AM,
IN"EGER, •,id REAL are included when needed. Some examples of the
DFFINE statement are:

DEFINE X AS A REAL VARIABLE


DEFNE X 1S AN INTEGER VARIABLE
DEFINE X AND Y kS INTFGEk VARIABLES
DEFINE X, Y, Z AS VARiABLfS
DEFINE X AS A VARIA5LL

In later iections, the NORMALLv and DEU';NE statements are ex-


pandea to include more than mode definition, as mode is but one of
several properties that can le used to desctibe variables. These
descriptors will be Pdded to the mode specification; aometimes mixes
of NORMALLY and DEFINE statements will be ueed in a program's preamble.
When a variable is defined with a certain mode it can only be
used in ways that art consistent w,.:h its definition. One source of
error is reading data from punched Zards that conflict with the form
in which variable values can be stored. Table 2-1 specifies the
actions taken when different combinations of data and variable 1.!fi-
nitions occur.

2-OL" £FR.ESSION W)DE.5

While statements that cLmbine INTEGER and REAL variabies are


allowed, a programer should he aware of the way in wnich computations
are carried out whenever "mixed mode" expressions are used.
(1) Arithmetic expressions of the form A oD B, where op is
any of the arithmetic operations , nd ', are

A and B represent variables of -,'ecified mode, or constants of


that mode.
-32-

Table 2-1

REAL-INTEGER INPUT DATA CONVERSIONS

Data Variable
Punched as Defined as Action
_I__

INTEGER INTEGiR Data value stored in variable


INTEGER REAL Data value converted to decimal representation
and then stored in variable; e.g., 55 stored
as 55.0
REAL REAL Data value stored in variable
REAL INTEGER Program termin~ates with error message; not
possible to store fractional value in integer
representation

INTEGER if both A and B are INTEGER


REAL if either A or B is REAL
t
(2) Expressions A/B are always REAL;
(3) Expressions A**B are always REAL.
Compound exprensions are evaluated from left to right as a se-
quence of simple expressions that are evaluated according to the
above rules. In the following examples, if A, B, and C are INTEGER,
then

A/B + C is REAL
A + B + C is INTEGER
A**B + C is REAL

When an expression appesrý. on the r!ght-hand side of a '_ET state-


ment or in an ADO or SUB3TRACT statement, and its -wode differs from
the mode of the variable on the left-hand side, thie expression is con-
verted to the mode *:f the variable before the value of the variable
is changed. When the arith.setic -txpresMion :onstituents of logica'
expressions differ in mode, all INTEGER expresaions are converted to

Two INTEGER exprossions car. be divided to yield ý truncated


INTEGER resu't by a procedire dercribed in ,'ec. '-•.
-33-

REAL before evaluating the logical expression as true or false.


Conversions from INTEGER to REAL are straightforward. An INTEGER
ro REAL conversion takes the whole number that is the value of an
INTEGER variable and converts it to a REAL number with the same value;
25 becomes 25.0, -11 becomes -11.0, and so forth.
REAL to INTEGER conversions are more complex. REAL values are
rounded to whole numbers Lf adding +3.5 to the variable if its value
is positive or -0.5 if it is negative, ana truncating the result. If
X is INTEGER and e is some REAL valued expression (formeed according
to the above rules), then

LET X - e sets X - 0 if e 3 0.2 since


0.2 + 0.5 - 0.7 - 0
LET X - e sets X 1 if e = 1.4999 since
1.4999 + 3.5 - 1.9999 - 1
LET X = e sets X - 2 if e - 1.50000 since
1.50000 + 0.5 - 2.0000 - 2

2-03 SUBSCRIPTED VARIABLES

Variable names can be used to identify more than one quantity.


This feature is particularly useful in programs dealing with data
that have a regular structure, e.g., data in the form of lists or
tables. Lists and tables are examples of iurrxys. Individual data
items in an array are called ei'ern's of the array. A s~imple list
of items (Fig. 2-1) is called a one-dimensional arrv;; a table of
items (Fig. 2-2) is called a two-dimensional array; in general, a

I
data collection that has n reference indices, as a position in a list,
or a row and column location in a table, can be described by an
c
'-.:;.L-wznzi array.

Fig. 2-1 -- A list structure; a one-d•-r•tnsO al a'rAy

1
-'4-

Column I Column 2 Column 3 Column 4 Column $

Row

Row 2

RIt• 3

Fig. 2-2 -- A table structure; a tweo-dimensional array

The elevmnts of the array shown in Fig. 2-1 can be described by


an i•entifyiat na, LIST for example, and an index nber which can
"asum integer values from 1 to the total numb%, if elew-nts in the
list. The array nme Is used to identify the collection of elements;
the indax number. called a eubscr.pt, enclosed in parentheses after
the array nme, is used to denote particular elements. Thus the first
elemnt in the array LIST im called LIST(O). the fifth elemnt LIST(5),
and the Ith elemnt LIST(I).
Groups of variablas that have a one-dimansional array structure
can therefore be described by an identifier and a single subscript.
Figure 2-3 shows the list of FiX. 2-1 with the individual element
ns inserted. Each element's subscript denotes its positiom in te
structure of the list; the value of the third element in the array it
in the variab'.e LIST(3). the value of the seventh element in LIST(7). etc.

F T(
11 UST( UST( 1) ST( J UST(di USrl1) LIST($ ULT (,I)

FIg. 2-3 -- Eleients of a orot-dlmearstonal; rray calltd LIST

Variables vith a tvo-dinensional array structure can be described


by an identifier and a pair of su&ecripts. The identifier (as &vaere)
is the nsme of the array; each sou.-ript denotes an elemnt lcatton
in a coordinate dimension. In Fit. 2-4, t?-e first subscript is used
** the elemt location in tfle rcw direction, and the eeconJ as zhe
esl nt location in the col;jm direction. Array elelmnt. are epecified
-35-

Column Number
1 2 3 4 ,

I TABLE( 1.1) TASLF( 1. 2) TABLE( 1.3) TABLE. I ABLE(I.)

Row Numnbe 2 TABLI(2. 1• TASLE(2.2) TABLE(2.3) TABLE(2.4) TABLE(2.5)

3TABU (3, 1) TABrA(3.2) TABLE(3.3) TAbLE( 3 4) TABLE (3. 5)

Fig. 2-4 -- Elements of a two-dimensional array called TABLE

by vriting their respective subscripts, enclosed in parentheses at,.-


separated by a comma, after the array name. Figure 2-4 shoas the
tvo-dimensional array of Fig. 2-2, here called TABLE, with the indi-
vidual element n-ams inserted. Note hay the subscript values indicate
each element's position in the structure of the table.
Arrays vith more than two dimensions can be desc-ibed in this
notation. A three-dimkasional array called CUBE might have elements
CUBE(I, J, K), a seven-dimensional array called SEVEN.DIM might have
elements SEVEN.DIM(A, B, C, D, E, F, G,.
Subscripted var-iabu " (the elements of arrays) can be INTEGER or

REAL valued. All elements of an array must have the same mode. If
their mode differs from that of the compiler's background conditions
it can be declared in a DEFINE statement in the same way as unwub-
scripted variables. For instance. if the assumed mode of all as vor
undeclared variables has been set to REAL, then we might write the
statement

CEFINE LIST AND TABLE AS INTT-jER ARRAYS

The words VARIABLE. VARIABLES, ARRAY, and ARRAYS can be used irter-
changvably to improve the readability of declarations.

The ::''' •, 2.. , w-eth r It has 0. 1, 1. 1 or

more s•b.scripts. must be defined in the preamble. A '-:.:

s1-t. m, ztan be inclui*dcin oiehsr MORhhLLY ,r DFINd

statements. dep id'ng on whother it is to apply as a Nhackjgr-u~nd4

Inya ",can So Used; AMD an's AiNO are no alkwI


-36-

condition or as a local property declaration. The phrase is written


somewhat differently in each case.
In a NORMALLY statement, a dimensionality specification phrase
can appear by itself or can be separated from a mode specification
phrase by a comma. An n-dimensional array background condition is
declared by any of the phrases,
DIMENSION = n DIMENSION IS n
DW = n DIM IS n

as in the ztatements

NORMALLY, MODE IS INTEGER AND DIMENSION = 2


NORMALLY, DIM - 3
NORMALLY DIMENSION IS .,MODE IS REAL
Th? mode and iimensionalicy phrases can appear in separate statements,
or in any order in thE same statement. As additional specification
phrases are added in later sections, phrase choices will be increased
but thp.se rules wiii net charge; the general form of the NORMALLY
statement is

'ORMALLY, specification phrase list

In a DEFINE statement the same general rules apply. A dimension-


ality specificati, can be made for a list of subscripted variables
with the dimcnsionality phrase n-DIMENSIONAL or n-DIM as in the state-
ments

DEFINE LIST AS AN INTEGER, 1-DIMENSIONAL ARRAY


DEFINE LIST AND VECTOR AS REAL, 1-DIMENSIONAL ARRAYS
DEFINE CUBE AS A 3-DIMENSIONAL, INTEGER ARRAY

Note that if a majority of program variables are arrays of a particular


dimension they can be defined by a NORMALLY statement, and the DEFINE
stctement can be used specify unslibscripted variables and subscripted
variabies of other dimensionality, as in

PREAMBLE
NORMALLY, MUDE IS INTEGER, DIMENSION = 2
DEFINE X, Y, Z AND Q AS REAL VARIABLES
DEFINE VECTOR AS A 1-DIMENSIONAL ARRAY
END
-37-

A variable must not, however, be used in more than one DEFINE state-
ment. It is permissible to write

NORMALLY, MODE IS REAL, DIMENSION = I

It is
DEFINE X AS AN INTEGER,

not permissible to write


O-DIMENSIONAL VARIABLE
I
NORMALLY, MODE IS REAL, DIMENSION IS I
DEFINE X AS AN INTEGER VARIABLE

DEFINE X AS A O-DIMENSIONAL VARIABLE

Each unsubscripted (0-dimensional) variable uses one computer


word to store its value; for each variable, e.g., MONEY, UNIT.COST,
there is a memory location that contains the value of MONEY, the
value of UNIT.COST. Similarly, each element of each array needs a
distinct computer word where its value can be stored. A one-dimen-
sional array with 10 elements uses 10 memory locations, a two-dimen-
sional array with 3 rows and 5 columns uses (3*5) - 15 memory locations,
and so forth.
A programmer does not have to make provisions f(- allocating
memory iccations Co unsubscripted variables; when the compiler ell-
counters a new unsubscripted variable, e.g., X, it automatically
assigns a memory word to that name. This is not true for subscripted
variables, for an array can have any number of elements, and unless
the compiler is told exactly how many, memory space cannot be assigned.
The RESERVE statement allocates computer memory to arrays. The
dimensionality of each array is indicated by asterisxs in subscript
positions; subscript size expressions declare the largest 'alue that
each subscript position index can assume. The product of these ex-
pressions is the total numbet of memory ceils allocated to each array.
Thus the statement

RESERVE X(*) AS 25, TABLE(*,*) AS 5 BY 27, CARGO(*) AS 18


AND CUBE(*,*,*) AS 3 BY 6 BY 10

allocates memory s'. ace for a one-dimensional array X with 25 elements


X(1), X(2), ... , X(25), a two-dimensional array TABLE with (5*27)=135
-38-

elements TABLE(I,1), TABLE(1,2), TABLE(1,3), ... , TABLE(1,27), TABLE


(2,1), ... , TABLE(2,27), TABLE(3,1), ... , TABLE(5,27), a one-dimensional
array CARGO with 18 elements, and a three-dimensional array CUBE with
(3*6*10)h180 elements.
Subscript size expressions need not be constants, as in the above
example, but can be arithmetic expressions containing variables, in-
cluding other subscripted variables that have been previously defined
and whose value has been specified. If such expressions are REAL,
they are rounded to INTEGER before they are used as array dimension
specifiers. Thus the statement

RESERVE X(*) AS N, TABLE(*,*) AS N BY 2*N, LIST(*) AS MAN.NUMBER


AND Y(*) AS S**T/2.5

defines the arrays X, TABLE, LIST and Y as long as the variables N,


MAN.NUMBER, S and T have previously been defined.
If a subscript expression in a RESERVE statement is 1, there is
only one element allocated to that dimension. The statement RESERVE
X(*) AS 1 defines an array X with one element X(l); the statement
RESERVE TABLE(*,*) AS 1 BY 3 defines a two-dimensional array with
three elements -- TABLE(1,1), TABLE(1,2), and TABLE(1,3). For all
practical purposes, these one- and two-dimensional arrays are equiva-
lent to the unsubscripted variable X and a one-dimensional array
TABLE(i), i-l, 2, 3, respectively.
A subscript size expression cannot be zero or negative. If an
attempt is made to reserve space with a zero- or negative-valued
expression, a program terminates with an error message.
A RESERVE statement can appear anywhere but in the preamble of
a SIMSCRIPT II program. It is an execu-,table statement, and until a
RESERVE statement containing an array name has been executed, storage
is not allocated for that array and its element values are not defined.
RESERVE statements are normally found at the head of a program. Each
subscripted variable must be reserved before it can be used -- a firm
rule to bear in mind. For example, the pair of statements

RESERVE LIST(*) AS 10 LET LIST(1)=1

allocates memory space to the array LIST before it assigns a value to


-39-

the element LIST(l). Each reserved array is initialized to zero after


memory space is allocated to it. If, either inadvertently or delib-
erately, a RESERVE statement is executed more than once, the SIMSCRIPT
II operating program recognizes that storage has already been allocated
to the listed variables and ignores all but the first RESERVE statement.
When two or more arrays have the same dimensions, an abbreviated
notation can be used. If A, B, and C are separate two-dimensional
arrays, the following statement allocates an identical amount of
memory space to each:

RESERVE A *,*), B(*,*), C(*,*) AS 5 BY 10

Any RESERVE statement can contain a sublist of this form among


its list of arrays, as in

RESERVE X(*) AS 5, FILE(*,*,*) AS 4 BY N+M BY 6, TABLE(*.*) AS 2 BY 3,


LIST1(*) AND LIST2(*) AS N+M, QUEUE(*,*) AS 3 BY Y,
A(*), B(*) AND C(*) AS 15

The dimensionality of an array is frozen when it is declared in


a DEFINE statement. Dimensionalities declared in NORMALLY statements
can be overridden by subsequent definitions in DEFINE statements, as
in the statements

NORMALLY, DIMENSIC'i = 2, MOOE IS RFAL


DEFINE X AS A 1-DIMENSIONAL ARRAY

Once a dimenaionality has been frozen, however, it must be used con-


sistently. In cases where there is disagreement between uses of an
array, thp SIMSCRIPT II rompiler takes the following actions:
When a subscripted variable has too few subscripts, the missing
subscripts are considered to be in the rightmost subscript position,
a I is inserted in each empty position and a warning message is issued.
For example, the incorrect LET statement in the following program
segment

RESERVE TABLE(*,*) AS N 3Y M LET TABLE(I) = I

is interpreted and compiled as LET TABLE(I,I) = I.


When a subscripted variable has too many subscripts, the extra
subscripts are considered to be in the rightmost subscript positions,
-40-

each extra subscript is deleted from the element reference and a


warning message is issued. For example, the incorrect LET statement
in the program segment

RESERVE LIST(*) AS 10 LET LIST(I,J) = 1


is interpreted and compiled as LET LIST(I) 1.
If an array name appears in a RESERVE statement without asterisks
to indicate its subscript positions, asterisks are filled in to make
the array agree with the dimensionality previously dezlared in a
DEFINE statement. If no dimensionality declaration has been made,
the number of subscript size expressions is assumed to be the dimen-
sionality. Thus, if an array has been declared as two-dimensional
by the'statement

DEFINE MATRIX AS A 2-DIMENSIONAL, INTEGER ARRAY

or if no dimensionality declaration has been made for the array the


statement
RESERVE MATRIX AS 5 BY 7

is compiled as

RESERVE MATRIX(*,*) AS 5 BY 7

without a warning message being issued. The form commonly used in


RESERVE statements is an array name without asterisks. It is shorter
to write, and, in the presence of DEFINE and NORMALLY declarations,
unambiguous. The long form is useful for program documentation.

2-04 USING SUBSCRIPTED VARIABLES


The following examples illustrate some uses of subscripted

variables:
(1) To read a number from a data card, and add together those
subscripted variables in a list that are greater than the number.
-41-

PREAMBLE
DEFINE NUMBER AS A 1-DIMENSIONAL ARRAY
DEFINE INDEX AS AN INTEGER VARIABLE
END
RESERVE NUMBER(*) AS 500
f program statements assign values to
the elements of the array NUMBER
READ N LET INDEX=1
'LOOP' IF NUMBER(INDEX) IS GREATER THAN N, ADD NUMBER(INDEX) TO SUM
REGARDLESS ADD 1 TO INDEX
IF INDEX IS LESS THAN 500, GO TO LOOP ELSE
PRINT 1 LINE WITH SUM AS FOLLOWS
SUM = * **
STOP END
" NOTE THAT INDEX MUST BE INITIALIZED TO 1 JN THE PROGRAM
" SUM IS AUTOMATICALLY SET TO 0 AT THE START OF EXECUTION
" NUMBER AND N ARE BOTH REAL BY IMPLICATION

(2) To search through a list .f numbers for all those that lie
between a lover and an upper bound; to print such numbers.

PREAMBLE
NORMALLY, MODE IS INTEGER
DEFINE LIST AS A 1-DIMENSIONAL ARRAY
END
READ N ''NUMBER IN LIST'', X "-LOWER BOUND" AND Y ''UPPER BOUND
RESERVE LIST(*) AS N LET INDEX=1
: { somewhere in here program statements
assign values to each element of LIST
'LOOP' IF LIST(INDEX) IS GREATER THAN X, "'AND"
IF LIST(INDEX) IS LESS THAN Y,
PRINT 1 LINE WITH INDEX AND LIST(INDEX) LIKE THIS
NUMBER *** = *w*.*
OTHERWISE
REGARDLESS
IF INDEX IS LESS THAN N, ADD I TO INDEX GO TO LOOP
ELSE STOP E14D

(3) To read a matrix (double-subscripted variable) of decimal


numbers and pairs of subscript values; to print the corresponding
matrix value and the matrix value whose subscripts are the reverse
of the pair read in.

II
-42-

PREAMBLE
DEF!NE MATRIX AS A 2-DIMENSIONAL ARRAY
DEFINE I, J AND N AS INTEGER VARIABLES
END
READ N ''THE DIMENSIONS OF THE ARRAY
RESERVE MATRIX AS N BY N READ ',IATRI,(t
'READ.LABEL' READ I,J ''THE SUBSCRIPT PAIR
PRINT 2 LINES WITH I,J,MATRIX(I,J) AND MATRIX(J,I) THUS
I=* J=* MATRIX(IJ) =
MATRIX(J,I) =
GO TO READ.LABEL END
Note that there is no test to terminate the program; it continues read-
ing cards and printing until there are no more data cards to be read.
(4) To illustrate the ,parentheses rule" as it Ppplies to the
evaluation of expressions containing subscripted variables.

Rule: Expressions containing parentheses are processed


from left to right and all parentheses are removed
before an expression's final value is computed.
In the parenthesis removal process, subscripted
variables are fetched from storage and their
values put in temporary unsubscripted variables.
Compound expressions containing parentheses are
simplified.

(4a) LET TEMP = X(I) + f(J) is executed by, first, performing


the substitutions X(I) - x, Y(J) - Z; second, by evaluating the ex-
pression X + Z; and third, by storing the result in the variable TEMP.
(4b) LET TEMP * X(I+J) + Y(J) is executed by, first, evaluating
the expression I+J i ; second, using this value, by performing the
substitution X(i) X; third, by performing the substitution Y(J) - z;
X
and fourth, by evaluating and storing the value of the expression X + Z.
(4c) LET TEMP= X(I + X(I+J) + 5) + Y(J + X(I+J) + 3) is executed
by eliminating parentheseu from left to right and simplifying nested
parentheses from the inside out. Computations and simplifications
are made in the following order:

+See Sec. 2-06 for a discussion of this statement. It reads the


N*N element values of MATRIX that were defined in the RESERVE state-
ment.
-43-

(1) I+J 1 (5) I+J i


(2) X(i) x (6) x(W )÷x
(3) I+x+5 j (7) J+x+3 Jj
(4) X(J) ÷z (8) Y(J) - q
(9) z+q - TEMP
±
Since common subexpressions may not be recognized, e.g., (1) and (5),
efficiency can be achievea by computing them in separate statements.
(5) To illustrate the use of INTEGER and REAL arrays in the con-
text of a realistic problem, the following program processes sales
order cards for a department store generating shipment orders, notices
of out-of-stock conditions, and final inventory reports. The program
assumes that several stores, located in different places, sell the
same items, that all merchandise is shipped from one cencral location,
and that top management is interested in the stores' performance.

PREAMBLE
NORMALLY, MODE IS INTEGER
DEFINE STOCK AS A 2-DIMENSIONAL ARRAY
DEFINE STORE AND ITEM AS 1-DIMENSIONAL ARRAYS
DEFINE PRICE, ITEM.INVENTORY AND STORE.INVENTORY AS
REAL, 1-DIMENSIONAL ARRAYS
END

RESERVE STOCK AS 100 BY 10, STORE AND STORE.INVENTORY AS 10,


ITEM, PRICE AND ITEM.INVENTORY AS 100
READ STOCK AND PRICE ''LAST PERIODS FINAL STOCK
" BALANCE AND CURRENT PRICES
'SALE' READ STORE.NUMBER, ITEM.NUMBER AND QUANTITY
IF ITEM.NUMBER IS ZERO, GO rO SUMMARY ELSE
IF STOCK (ITEM.NUMBER, STORE.NUMBER) IS LESS THAN QUANTITY
PRINT 3 LINES WITH STORE.NUMBER, ITEM.NUMBER, OUANTITY AND
QUANTITY-STOCK(ITEM.NNUMBER, STORE.NUMBER) THUS
STORE ** IS LOW ON STOCK OF ITEM NUMBER *
ORDER OF **** UNITS CANNOT BE FILLED
**** UNITS ARE BEING BACKORDERED
IET QUANrITY- STOCK(ITEMtlUMBERSTORE.NUMBER)
OTHERWISE SUBTRACT QUANTITY FROM STOCK (ITEM.NUMBER,
STORLE.NUMBER) PRINT I LINE WITH QUANTITY, ITEM.NUMBER
AND STORE.NUMBER AS FOLLOWS
S•IP **** UNITS OF ITEM *"* TO STORE **
GO TO SALE

*This is a function of the optimization procedures used in diL-


ferent implementations of the language.
-44-

'SUMMARY' LET I = 0
'LOOP' LET J = 0 ADD 1 TO I. IF I = 11, GO TO PRINI ELSE
'AGAIN' ADD 1 Tb J IF J = 101, GO TO LOOP ELSE
ADD STOCK(J,I; TO STORE() ''STORE SALES''
ADD STOCK(J,I) TO ITEM(J) ''ITEM SALES"
ADD STOCK(J,I)*PRICE(J) TO STORE. INVENTORY(1)
''SALES DOLLARS''
GO TO AGAIN
'PRINT' L`T J = 0
'NEXT' ADD 1 TO J. IF J = 101, GO TO OUTPUT ELSE
LET ITEM.INVENTORY(J) = ITEM(J)*PRICE(J)
" ITEM DOLL ARS''
GO TO NEXT
'OUTPUT' START NEW PAGE
PRINT 1 LINE AS FOLLOWS
SUMMARY REPORT AT END OF CURRENT PERIOD
SKIP 2 OUTPUT LINES
LIST STORE, STORE.INVENTORY, I1M, ITEM.INVENTORY
AND STOCK
STOP
END ''OF PROGRAM

2-05 CONTROL PIIRASES

A SIMSCRIPT II statement can be executed more than once by append-

ing a control phrase to it. This concept is illustrated by the example

FOR I = 1 TO 10, LET X(I) = 5

The phrase FOR I = 1 TO 10 controls the execution of the LET


statement following it, causing the statement to be repeated 10 times,
first with I = 1, next with I = 2, then with I = 3, and so on, until
it is executed for the last time vith I = 10. The effect of the
example is to set the first 13 elements of the array X equal to 5.
The general form of a controZ vhrase is

FOR variable - arith erpr1 TO arith exr2r BY zrit;: -'rrr

Any REAL cr INTEGER unsubocriptei variable can be used as the variable

in the control phrase. The first :ime a ,,ntr.ol:p:' statowe,:t (like


the LET statement above) is executed, the control phrase variable is
set equal to the value of expressionl; a type conversion is made if

See Sec. 2-li for a discussion of this statement.


-45-

necessary. If the value of expreson is not greater than that of


expression 2 (it usually is not), the controlled statement is executed.
After execution, the value of expression3 is added to the control
phrase variable, and if this new value is again less than expression.
the ccntrolled statement is repeated. This process continues, with
the control phrase variable taking on successively larger values until

it exceeds the value of expression 2. A coma at the end of a control


phrase is optional.
If the phrase "BY expression 3 " is left out of the control phrase.
as in the above example, a value of 1.0 is assumed for expresuion 3.
This short form of the cortrol phrase is convenient for executing a
controlled statement over a range of ruccessivt subscript values. The
longer form is useful for statements in which calculations involving
the control variable are performed, as in the program segment

FOR N - L.OW TO HIGH RY INCREMENT, ADD INCREMENT*N TO SUM

The foregoing statement does .iot operate on a subscripted vari-


able, but uses the properties of the control phrase to perform a
series of calculations that follow some prescribed order and accom-
plishes the same task as the statements

LET N - LOW
'LOOP' ADD INCKEMENT*N TO SUM
ADD INCREMENT TO N IF N<HIGH, GO TO LOOP ELSE...

Arithmetic expreswlons in control phrasL which have so far


been denoted as expression,, expression,, and expression3, from he-e
on will be labeled e 1 . e 2 , and e3. Each oue can be any legitimate
arithmetic expression; they need n-t be of the same mode, sinc. con-
versiono will be made if necessary. If any of the expressions are
REAL, all computations involved in -omputing the successive values
o! the control phrase variable, called v from here on, will he REAL.
-46-

Poesible Subscript _
Control Phrases Successive Values of v
FOR I - I TO 5. 1-2.3.4.5

FOR ! - -5 TO 5, -5,-4,-3,-2.-l,0.l,2,3,4,5,
FOR I - 0.0 TO 2.0 BY 0.5 0.0,0.5,1.0.1.5,2.0
! a 0 TO N BYM,
FOR I if Nis less than 10 the cn-
trolled statement will not be
executed
if N is at least equal to 10,
the controlled statement will
be executed with 1-10, 10+M,
l0+2*1, ... , lo+n*M until I
exceeds N

The above illustration shows that it is imossible to step back-


yard, as for example, I - 5, 4, 3, 2, 1, with this control phrase.
A variant of the phrase ix used fcr this purpose. The form is

FOR v BACK FROM e1 TO e 2 BY e3

Everything applicable to the forvard stepping control phrase


applies to this phrase; the only difference is in the direction in
which the control phrase variable changes value.
Control phrases can be n'stee together for dealing with arrays
of more than one dimension, an in

FOR I - 1 TO N, FOR J - ' TO M. LET X(I,J)-VALUE

Used this way, the control phrase on the left in said to be an outer
phrase, and the phrase on the right an inner phrase. In cvaputing
successive values of I and J, the inner phrase is stepped Th•rough its
entire range of values for each value of the outer conz.rol phrase
variable. The controlled stateent is executeJ each time . Thus, It
N - 3 and M - 4. the above stactý=nt vould be executed in the sequence
-47-

Step I J Statement Executed


1 1 '1 LET X(1,)) a VALUE

2 1 2 LET X(1,2) - VALUE


3 1 3 LET X0,3) - VALUE
4 1 34 LET X(1,4) - VALUE
5 2 1 LET X(2.1) - VALUE
6 2 2 LET X(2,2) - VALUE
7 2 3 LET X(2.3) - VALUE
8 2 4 LET X(2,4) - VALUE
9 3 1 LET X(3,1) - VALUE
10 3 2 LET X(3,2) - VALUE
11 3 3 LET X(3,3) - VALUE
12 3 4 LET X(3,4) = VALUE

An indefinite number o. phrases can be nested together in this


way. Each successive phrase is au, outer phrase to its right-hand
phrase, and an iziner phrase to its left-hand phrase. Control vari-
ables of outer phrases can be used in the expres.ions e 1 , e 2 , and e
of inner phrases, as their values are Jefined within these phrases.
Tnus de might have the nested phrases

FOR I 1 TO N, FCR J I TO 1. LET X(IJ)


1 - 0

If N 3 this statement will be executed as

Stec 1 i J Statement Executed


I I I LET I(I1, ) - 0
2 g I L (2,1) 0
LUT 1(2.2) - 0
•. 3 1 LET x(3,1) * S

3 Z LET i(3,'} -
3 3 LET ix3,3) 0

rablo contaitns & list of the 51teCIIrt '4 sitest nts sc:'
thus far that are ::rtra7.asl. sn'V otc':o. Ciban~tr,:

ph ras s.
-43-

Table 2-2

SUBSCRIPT STATEMENTS

Controllable Uncontrollable
Statement Types Statement Types

LET IF
ADD GO TO
SUBTRACT STOP
READ NORFALLY
PRINT DEFINE
START NEW PREAMBLE
SKIP END
RESERVEa

alow this might usefully be done is


explained in Sec. 2-08.

For example:
(a) FOR I = 1 TO MAX, READ X(I)
reads the successive values X(1), X(2), ... , X(MAX)
(b) FOR X = 1 TO N, ADD X**2 TO SiM
N 2
computes I X N*X**2
X=1
(c) FOR I = 1 TO N, ADD X(I)**2 TO SUM
N
computes i I
I=1
(d) PRINT 1 LINE AS FOLLOWS
INDEX VALUE
FOR IN•DEX = 5 TO 10, PRINT 1 LINE WITH INDEX AND
VALUE(INDEX)
**
LIKE THIS
** **

prints a labeled list of numbers stored in the


one-dimensional array VALUE.

2-06 3EADING SUBSCRIPTED VARIABLES

Subscripted variable values can be read by the READ statement in


several ways. The statement can be used to read individual elements
of arrays, entire arrays, or elements of arrays under the control of
one or more control phrases. In the following paragraphs let LIST
-49-

be a singly-subscripted variable defined by the statement RESERVE


LIST(*) AS 10.
Individual elements of arrays are read by listing their names
(the array identifier followed by the appropriate subscript expres-
sion(s) enclosed in parentheses) in the list of a READ statement.
Values of LIST(l), LIST(5), and LIST(9) are read by the statement

READ LIST(1), LIST(5), LIST(9)


A variable list can contain array elements whose subscript designators
are expressions, such as LIST(N*M+2/J) or LIST(I), as long as the
variables appearing in these expressions have had values assigned to
them. They are assigned if they appear in a READ statement before ¶
their use in the same statement as subscripts, as in

READ N,M, LIST(N), LIST(LIST(N)+M)

This example shows that both unsubscripted and subscripted variables


can appear in the same READ statement list.
Entire ar-ays can be read by using only their names in a READ
list. READ LIST reads the 10 elements of LIST, as defined by the
RESERVE statement; numbers are read and assigned to the elements of
LIST in increasing subscript order, the first data item is assigned
to LIST(1), the next to LIST(2) and so on. If LIST were a multi-
dimensional array, the data would be asaigned to successive elements
whose subscripts change in increasing order, with the last subscript
positicn varying most rapidly. A two-dimensional array is read in
row by row, as in LIST(1,1), LIST(i,2), LIST(1,3), ... , LIST(1,N),
LIST(2,1), LIST(2,2), ... , LIST(2,N), etc.
Mixtures of unsubscripted variables, elements of arrays, and
entire arrays can be read in one READ statement. If LIST and VECTOR
are one-dimensional arrays, TABLE a two-dimensional array, and X and
Y unsubscripted variables, the statement

READ X, LIST(7), VECTOR, TABLE, Y, LIST(Y)

reads a data item and assigns its value to X; reads another data item

tThe statement's variable list is processed from left to right.


-50-

and assigns its value to LIST(7); read& as many data items as there
are elements in the array VECTOR ind assigns them to the elements of
VECTOR; reads as many data items as there aro in the array TABLE and
assigns them to the elements of TABLE; reads a data item and assigns
it to Y; and reads a data item and assigns it to thi element of LIST
indexed by the subscript Y.
A subscript control phase can also be used to control the selec-
tion of array elements in a READ statement. The statement

FOR INDEX = L TO N, READ LIST(INDEX)

r-ads N data items and assigns their successive values to the elements
LIST(L), ... , LIST(N).
Some examples illustrate a few of the many forms a READ statement
can take. X, Y, and Z are subscripted variables defined by the state-
ment

RESERVE X(*),Y(*) AS 4, Z(*,*) AS 4 BY 4

while A, B, and C are unsubscripted variables.

(1) READ A,B,C,X(1),Y(3),Z(2,3) reads six numbers and assigns


their values to A, B, C, and to the three subscripted
variables X(1), Y(3), and Z(2,3).
(2) READ A, X, B reads six numbers ud assigns their values to
A, X(1), X(2), X(3), X(4), and B, respectively.
(3) READ A,B FOR 1=1 TO 3, READ X(I) READ Y reads nine numbers
and assigns their values to A, B, X(1), X(2), X(3), Y(1),
Y(2), Y(3), and Y(4), respectively.
(4) FOR I = I TO 4, READ X(I) AND Y(I) reads eight numbers and
assigns their values to X(1), Y(1), X(2), Y(2), X(3), Y(3),
X(4), and Y(4), respectively.
(5) READ Z reads sixteen numbers and assigns them to
Z 1.1) Z(1,2l Zý;,31ý
Z 1,4)
Z(2,1) Z(22
Z Z2,4)

Z 3,1) Z (3,2) Z(3,3) Z 3,4)


Z(4,1) Z (4,2) Z(4,3) Z(4,4), respectively.
(6) FOR I - 1 TO 4, FOR J 1 TO 4, READ Z(I,J) reads sixteen
numbers and assigns then as in (5).
(7) FOR I - I TO 4, READ Z(2,I) reads four numbers and assins
them to the elements of the second row of Z: Z(2,1), Z(2,2),
Z(2,3), Z(2,4), respectively.
-51-

The above examples show that a control phrase does not control
the index of a variable within a READ statement, but controls the
entiz-e READ statement. Thus, each variable that appears in a con-
trolled READ statement should contain the control variable as a sub-
script; if it does not, successive data values are assigned to this
variable as the control phrase iterates over the range of the control
phrase variable. This is seen in the statement below, which reads
and assigns six successive values to the unsubscripted variable A and
the subscripted variables X(I). Naturally, all but the last value of
A is lost,

FOR I = I TO S, READ A, X(1)

2-07 CONTROL PHRASES EXTENDED TO INCLUDE CONTROL


OVER MORE THAN ONE STATEMENT

The concept of a control phrase (sometimes called a FOR phrase)


can be exianded to permit the phrase to control not one, but an arbi-
trary number of statements. Statements to be controlled as a group
are enclosed between the words DO and LOOP. A control phrase controls
grouped statements in exactly the same way it controls a single state-
ment. As an example, consider a program that reads data, examines
each item to see if it has a certain property, and indicates by a
coded reply whether or not each item passes the property test.

PREAMBLE
NORMALLY, MODE IS INTEGER DEFINE X AND TEST.NUMBER AS REAL VARIABLES
DEFINE CODE AS A 1-DIMENSIONAL ARRAY
END
READ NUMBER.OF.SAMPLES AND TEST.NUMBER
RESERVE CODE AS NUMBER.OF.SAMPLES
FOR I = 1 TO NUMBEROF.SAMPLES,
DO
READ
X
IF X IS LESS THAN TEST.NUMBER, LET CODE(I) - 1
TO SUM
LOOP REGARDLESS ADD CODE(1)
PRINT I LINE WITH 100*(SUM/NUMBER.OF.SAMPLES) THUS
PER CENT ITEMS LESS THAN TEST NUMBER = **.**
STOP END
In the foregoing example the statements READ, IF, LET, REGARDLESS,
and ADD appear between the statements DO and LOOP. The logic of
-52-

these statements is exercised once for each iteration of the control-


ling FOR phrase.
A DO loop (as we shall call this expanded structure from here
on) can also be constructed from a backward iterating FOR phrase. Its
grammar can often be improved by the optional wofis THE FOLLOWING or
THIS after the word DO, and the substitution of the word REPEAT for
LOOP. Thus we can write

FOR N = 1 TO 10, DO THE FOLLOWING...REPEAT or


FOR N = I TO 10, DO...LOOF and
FOR I BACK FROM 10 TO 1, DO THIS...LOOP or
FOR I BACK FROM 10 TO 1, DO...REPEAT

Normally, a DO loop is executed over the entire range of a FOR


phrase. The value of the control phrase variable upon normal exit
from i'loop (through the LOOP statement, that is) is the first com-
puted value of V that fails the continuance test. If the loop is
terminated at any other time, as by a GO TO statement within c loop
that transfers control to a statement outside the loop, the variable
retains its current value.
Since the variable V, and the control expressions e 2 and e3 can
be variables or expressions containing variables, they can be re-
computed within a loop. This can affect the sequence of values of
the control phrase variable, either shortening or extending it, and
it can affect the computations performed by the program. The follow-
ing two examples illustrate the use of recomputed FOR phrase values
within a loop:

(1) RESERVE VALUE(*) AS N


FOR V = I TO J BY K, DO THE FOLLOWING
IF VALUE(V) < V, ADD 1 TO K ALWAYS ADD VALUE(V) TO SUM
LOOP
(2) FOR V = I TO J BY V*2, DO ... LOOP

In Example (2), if I z 1 initially, the variable V takes on suc-


cessive values of 1, 3, 9, 27, 81, ... , until V is greater than J.
As implied above, labels can be used within a loop to transfer
control around statements in the loop, or to end the loop prematurely
by transferring to a statement outside it. It is possiblp 'o transfer
in and out of loops at will as long as each transfer rec 0.-. zes the
-53-

organization of the FOR phrase mechanism and does not expect more

from the compiler than it is able to do. Each FOR phrase is compi'ed
into a series of program steps that work, roughly, as follows (the
word rozughly is used since variations of the FOR statement require
different treatments, e.3., the direction of the inequality will
change in the IF test when a BACK FROM phrase is used):
The program

FOR V=e 1 TO e 2 BY e
3
DO
Statement group
LOOP

is compiled into the program

LET V=e,
GO TO L.2
'L.1' ADD e t0 V
'L.2' IF V ý e 2 ', GO TO L.3
OTHERWISE

Statement group

GO TO L.1
'L.3: continue with program

L.1, L.2, and L.3 are local labels that the compiler constructs; they
cannot be used by a SIMSCRIPT II programmer.
DO loops can be nested within one another for control over sub-
scripted variables with two or more subscripts. Recall that subscript
indexing takes place within the bounds of the DO and LOOP or REPEAT
statements. To print a matrix of numbers, we might write:

FOR I = 1 TO N, DO
FOR J = 1 TO M, DO
PRINT 1 LINE WITH I, J, MATRIX(I,J) AS FOLLOWS
MATRIX(*,*) = *.***
LOOP "ON J, THE SECOND SUBSCRIPTt
REPEAT ''ON I, THE FIRSr SUBSCRIPT

tThe careful reader will note that this statement is not required,
as the preceding FOR only controls one statement. In fact, neither
the preceding DO nor the following REPEAT is required.

-4.' ~ -
-54-

This example can be clarified by using indentation like that


used with nected IF statements.

FOR I - 1 TO N, DO
FOR J - I TO M, DO
PRINT 1 LINE WITH I, J, MATRIX(I,J) AS FOLLOWS
MATRIX(*,*) .
LOOP ''J''
REPEAT 'I''

If N = 2 and M - 3, this program prints:

MATRIX(1,1) - -----
MATRIX(1,2 - ....
MATRIX(1,3 - ....
MATRIX(2,1 ------
MATRIX (2.2 - ....
MATRIX (2,31 =

S2-08 STRUCTURES--POINTER VARIABLES


PROGRAIMR-DEFINED ARRAY

It was previously stated that each array is assigned a ntumber of


computer words equal to the product of its subscript-size expressions.
This is not quite correct. Each array has as many computer words as
contain the values of its elements, plus additional words that point
to these element values. This section describes how these pointer
wozrd are used to connect array storage, and how they can be used to
a programer's advantage.
Each array has a base pointer that points to the array as it is
structured in memory. For a one-dimensional array X, the base pointer
is named X(*), for a two-dimensional array Y, the base pointer is
named Y(*,*), and so on. The base pointer is used in a RESERVE state-
ment when vemory space is allocated to an array. The function of the
RESERVE statement is to allocote computer words to an array and assign
the internal location of these words as the value of the base pointer.
In the following examples, one-, two-, and three-dimensional
arrays are used to de..,rihe how pointer words are employed in struc-
turing arrays. The structure of higher dimensional arrays follows
directly.
The base pointer of a one-dimensional array points directly to
data elements that are stored contiguously in whatever mode the array
-55-

has been declared. The base pointer, whose value is a computer loca-
tion, is always in INTEGER mode. A one-dimensu"onal array X, allocated
storage by the statement

RESERVE X(*) AS 10
is stored as:

ELEMENTS
X(1)
X(2)
X(3)
BASE POINTER X(4)
X(5)
X(*)
X(6)

X( 6)
X(9)
X(lO)

The base pointer is in a computer word that is separated from the


array elements. The actual locations assigned to the elements depend
upon the order in which RESERVE instructions have been executed in a
program.
The base pointer of a tvo-dimensional array points, not to its
doubly-subscripted data elements, but to an array of pointers that,
in turn, point to the elements of the rows of the array. The base
pointer and all the row pointers are in INTEGER mode; the data element
words are in whatever mode the array has been declared. A two-dimen-
sional array X, which aes been allocated storage by the statement

RESERVE X('*') AS 5 BY 3

is stored as:
-56-

ELEMENTS

X(1' 1)
ROW POINTERSX(12)
'((1 .3)

X(1P ,)

BASE POINTER X(2, 0) X(.. '3

( 1X(3,)

X(43,) X(3. 12)


X((4.'2

XX(5..
X('5 1)

X(5, 31

A three-dimensional array is treated similarly -- the base pointer


points to an array of row pointers, each of which points to an array

of x!,n'w pointers, of which each, in turn, points to an array of data


elements. A three-dimensional array X, which has been allocated

storage by the s~atement

RESERVE X(*.,') AS 5 BY 3 BY 2

is stored as:
-57-

COLUMN POINTER -LEMPENTS


- -I -- f=
X(l. 11. I..l. 2)

X(l, 2. 1, 2,_I)j

X(l, 3,
LX( 3, 2)

X(2, 1, 1)
X(2, 1, X(2.1,2)
1
11
r X(2, 2, Y)l
X(2, 2,

ROW PO',NTER
NTER X(2, 3, 1)
X(2.
X(l. . . X(2. 3. X(2, 3, 2)

X(3, 1. tj X(3,1,2)
BASE PO!NTER

X(ol X(3. X(3,2, 0)


ImLnLl 2_.2221
f FX(3,
X(4, -- 'I[ X(3, 3,

X(4, 1. X(4, 1. 1)
X(5- 0. 0)
E4., 1.2)
XG 2)

f I X(4, 27,71)
X(4.2,

X(4. 3,

x(s, 1,
4 ý1,
EX(5, 2)l

X(5. 2.
wl
X(5, 3, 1)
5 3. ý2)
kXk
-58-

Every element reference with at least one asterisk in its sub-


script list is a pointer; every element reference without asterisks
in its subscript list is a data word. Pointers are cascaded from one
dimension to another, ending at a dat& word array.
All of this, while seemingly complicated, need not be bothersome
to a prograrser. Arrays are allocated storagp by the RESERVE state-
ment, and elementi; (subscripted variables) are referenced by previously
described methods; pointer words need not be mentioned explicitly,
nor need the manner in which rows and columns of arrays are linked be
taken into consideration. A progranmmer has the advantage of a flexible
array mechanism without being penalized if he does not choose to use it.
The pointer mechanism provides two primary advantages. The first
and most apparent advantage is that the potential for fitting large
programs into core storage is increased because it is unnecessary to
loiate an unused block of core capable of holding an entire array, it
being necessary only to find a number of smaller blocks that can be
linked together. The second, and potentially more useful, advantage
is the ability to manipulate pointers as though they were data values.
This permits the construction of arbitrary data structures to suit
the specific requirements of different problems, and is accomplished
by allowing the asterisk notation used above for pointers to appear
in all SIMSCRIPT II statements. The notation is meaningful only in
a small number of statements, of course. The utility and application
of this feature are best described in a series of examples.
(1) It is used to construct a "ragged table," a two-dimensional
array with a different number of elements in each row. The construc-
tion follows:
(a) Set up a base pointer and an array of row pointers

RESERVE TABLE(*,*) AS 5 BY *

This statement assigns an array of five elements, each of which con-


tains an unassigned pointer, to the base pointer TABLE(*,*). The
asterisk in the array assignment clause 5 BY * indicates that only
pointers, not data values, are to be stored. After execution of this
statement, the following structure exists in memory:
-59-

ROW POINTERS

STABLE('. ")TABLE(3.)

TABLE (4, "


TABLE (5, "

The base pointer points to the array of row pointers; the row pointers
do not point to anything since arrays have not yet been assigned to them.
(b) Set up a loop to assign data arrays to each of the row

pointers. Since a dimension must be given for each row, read a value

for each row from a dat. ard.

FOR I=1 TO 5,
DO READ ")
RELERVE TABLE(I,*) 'PS D
L3OP

The RESERVE statement assigns an array of D elements to each row


pointer TABLE(I,*), as I varies from 1 to 5. If the values of D
read are 4, 2, 6, 1, and 3, re3pectively, the final, ragged table
structure locks as follows:

DATA ELEMENTS

TABLE(1, 1)
TABLE(], 2)

TABLE(1, 3)
ROW POINTERS

TABKE (1,' TABLE(2, 1)


•[f TABLE (2, 2)

I. ABLE(3, 2)
BASE POiNTER

'IABLE(3,4)
3)
TABLE(- s) lop; TABLE(3,*) [3 TABLE(.1,
TABLE(3.4)
1

TIBLE(3 5)
TABLE (4, TABLE(3,6)
TABUi:(4, 1)
TABLE (5 ")•w,•{ rABLE(5. 1)

I'ABLECS.2
-60-

The ragged table TABLE(I,J) can be used the same as any rectangular
array, The only care a programmer must exercise is to ensure that
he does not ask for a nonexistent array element, as, for example,
TABLE(4,3) in the above illustration.
(2)
Section 2-03 indicates that once an array has been reserved
it cannot be reserved again. To prevent this from happening, the
SIMSCRIPT II system ignorps instructions to reserve an array when the
pointer to the array has a value in it. When a program is first ini-
tialized, all array pointeýz. are zero, makS-g the first RESERVE pos-
sible. After this, the presence of a nonzero value in a pointer
variable dictates whether or not a reserve w-l' ?e exdcuted.
At timas ft is useful to be able to perform multiple ai•ray zeser-
vations, kev.ping track of array pointers as they are _eplaced, This
can be done by stcring a pointer, setting -.L to zero, an: executing
a new RESERVE statement. Althou:'b the pointer variable will point
to the latest array that is rese.-vfd, it is possihie a.: any tiue to
restore it to a previous ,alue (which sti. )_ ptnts t; an array of
values in memory) and use those previously computed values. The
example below illus.ratfG how such a mechanism ca- be employed:
A pLogram is to De developed that aiores gcaea!ogical informa-
tion in the form of a family tree. Sidc a tree hdq an individual at
its apex, his parents at the next level, his parents' parents below
that, and so on. Figurc 2.5 Llluatratee a family tree containing

four levels of genealogical informatiur..

INDIVIDUAL ................... .. .. . .

PARENT ................. - r2 3

GRANDPAI~NTs.. 4 5 7

GPEAT- lF,
GRANDPARENTS 8 9 lu 12 F, 1

Fig. 2-5 -- Fami ly tree


-61-

This information can be stored in a rectangular array. as depicted


in Fig. 2-6. While simple to do, it is wasteful of coviuter memory
because of all the empty cells.

2 3

4 5 6 7

8 9 10 11 12 13 14 15

Fig. 2-6 -- Family tree stored In


a rectangular array

A more memory-conserviag storage scheme is shown in Fig. 2-7. It


allocates no more computer words than there are data to store. Our
task is to show how this scheme can be programmed and used utilizing
the t,ýchnique of array pointers.

2 3

4 5 6 7

8 912 1 13 14 151

Fig. 2-7 -- Family tree stored


in a ragged table

In the folluvwng progtam, the data of each level is stored in an


array TREE. At level one, TREE has one element, at level two, two
elements, at level three four elements, ... , at level N, 2 N-1 elements.
The array pointers for the N arrays are stored in a list called LEVEL.
It has N elements, one for each level of the genealogical tree.
-62-

Assume that we are given the number of levels in the tree and the names
(co 4 ed as integer numbers) of the family members arranged in proper
order on punched cards. We first construct a tree with the family
data suitably arranged. The following program does this:

PREAMB'E NORMALLY, MODE IS INTEGER


DEFINE LEVEL AND TREE AS 1-DIMENSIONAL ARRAYS
END

READ N RESERVE LEVEL(*) AS N


FOR 1=1 TO N,
RESERVE TREE(*) AS 2**(I-1)
READ TREE
LET LEVEL(I)=TREE(*) LET TREE(*)-O
LOOP
END
For N-4, the memory structure at the end of program execution looks
as follows:

LEVEL TREE

IZIZ
3 -1,15 17 ,7F
4 8 1 9 10 111 12 13 14 is

To print out a person's Kth level ancestors, one writes

READ K
LET TREE(*)-LEVEL(K)
LIST TREEt
To pick out specific ancest)rs, one can search through the tree until
the correct code is found using the following program:

1This
statemnt displays an entire array; set Sec. 2-11.
-63-

READ CODE
FOR I-I TO N,
DO LET
TREE(*)=LEVEL(I)
FOR J-1 TO 2**(I-l).
DO
IF TREE(J) EQUALS CODE, GO TO PRINT
OTHERWISE
LOOP
LOOP
PRINT 1 LINE WITH CODE AS FOLLO'S
UNABLE TO FIND AN ANCESTOR WITH THE CODE **
STOP
'PRINT' PRINT 1 LINE WITH CODE, J AND I AS FOLLOWS
ANCESTOR ** FOUND IN POSITION * OF LEVEL *
STOP
END

(3) The pointer mechanism can be used to set up an array whereby


some rows contain INTEGER numbers and some rows REAL numbers. Usually
this cannot be done, since an array name has a single mode value, but
it can be accomplished if all data items are atored in a single array
and dummy arrays used to access the data rows for processing.
(a) Declare three arrays as follows:

DEFINE TABLE AS A 2-DIMENSIONAL, REAL ARRAY


DEFINE WHOLE AS AN INTEGER,1-DIMENSIONAL ARRAY
DEFINE DECIMAL AS A REAL.1-DIMENSIONAL ARRAY

(b)Allocate memory space to the array in which the data


are to be stored.

RESERVE TABLE(*,*) AS 10 BY 10

(c) Read INTEGER values into the fourth row of the array
by using the statements

LET WHOLE(*)-TABLE(4.*)
READ WHOLE

"The first statement sets the base pointer of the one-dimensional array
WHOLE equal to the row pointer of the fourth row of TABLE. This has
the effect of assigning the 10 data element values of thp fourth row
of TABLE to WHOLE -- both TABLE(4,*) ard WHOLE(*) point to the 9~
memori locations. The second staLement reads 10 data values into
the array WHOLE, vhich is also a row of TABLE. They are read as
-64-

integers, since WHOLE has been declared an INTEGER array. The READ
statement knows ho.. :y elements to read, since every pointer word -

in this instance ViOLE(*) -- knows the number of elements it points


to, as well as pointing to the elements.
(d) Read REAL values into the seventh row of the array
TABLE by using the statements

LET DECIMAL(*)=TABLE(7,*)
READ DECIMAL
or the statement
FOR I=1 TO 10, READ TABLE(7,I)
Both statements can be used, since TABLE has been defined as a REAL
array.
(4) The pointer mechanism can be used to make the processing of
a three-dimensional array more efficient by eliminating the necessity
of recomputing two subscripts each time an element is accessed in a
FOR loop. The program segment described in (a) can be made more
efficient by rewriting it as shown in (b).

(a) FOR I=1 TO 10, TREAD CUBE(J+7,K+L,I)


(b) LET DUMMY(*)=CUBE(J+7,K+L,*)
FOR I-1 TO 10, READ DUMMY(I)
where DUMMY has been defined as a oie-dimensional
array of the same mode as CUBE and has not had
storage reserved for it.

The revised statement eliminates the need for recomputing the sub-
scripts of CUBE -:t are not affected by the FOR loop every time a
new element is accessed. Little additional memory space is taken,
for the array DUMMY never has more words allocated than are needed
for its base pointer.
The use of pointer words thus greatly enhances a programmer's
ability to construct and use data structures, and its applications
are manifold; for inrtance, rows of mat,-ices can be interchanged by
simply changing pointer values, and large -natrices with many identi-
cal rows can be compressed by having several pointers point to the
same array.
The most genersl form of the RESERVE statement illhusrating the
-65-

full power of the pointer system can now be stated as

RESERVE pointer list AS array dec.ription

where a pointer list consists of a list of subscripted variables


having at least one asterisk in their subscript list and an array
description describes the size and content of the array or arrays
being reserved and pointed to. If an array descriptioa does not con-
tain any notational asterisks, as in the descriptions 5, 6 BY N,
3 BY M+7 BY 4, and N BY M BY X**? BY 2, a data array is reserved and
pointed to by the pointer mentioned. If an array description contains
a notational asterisk, the asterisk indicates that pointer words are
being reserved and that subsequent RESERVE statements allocate data
arrays to them. It is only meaningful to have a single notational
asterisk in an array description, as this is sufficient to indicate
that pointers, not data, are being allocated. As noted in example (1)
of Sec. 2-08, this asterisk must come after any constants and expres-
sions that define the dimensions of prior subscript positions. The
following RESERVE statements illustrate these concepts:

(1) RESERVE ARRAY(*,*) AS 5 BY 7


(Allocates a 5 by 7 data array.)
(2) RESERVE ARRAY(*,*) AS 6 BY *
(Allocates six pointer variables.)
(3) RESERVE ARRAY(I,*) AS 12
(Allocates twelve data elements to a pointer variable.)
(4) RESERVE ARRAY(*,*) AS 5
(Allocates a five-element array to a declared two-dimen-
sional variable. Although this statement will compile,
it should be used carefully for it will usually cause a
programing error. The array elements cannot be accessed
directly, as ARRAY is a two-dimensional variable. To be
accessed, the pointer must be transferred to a one-dimen-
sional array pointer.)
(5) RESERVE ARRAY(*) AS 5 BY *
(Similar to (4), but with the dimensionality problem re-
versed if ARRAY has not been defined as two-dimensional.)
-66-

(6) RESERVE X(*),Y(*) AND Z(*) AS N+3


(Illustrates that several pointers can be assigned storage
space of the same dimension and function (pointers or
data). Each pointer, of course, is assigned a separate
block of storage.)
(7) RESERVE X(*) AS 5, TABLE(J,*) AS N+8
(Illustrates that several array reservations can be made
in the same RESERVE "-tatement. In this example, the first
one allocates a five-element data array to a base pointer
X(*) and the second allocates an N+8 element data array
to a row pointer TABLE(J,*).)

Two features are provided that make the uce of pointers easier.
The first concerns the physical act of writing programs and the second,
the task of operating with arrays of unknown size.
(1) A base pointer can be written as X(*) regardless of the num-
ber of its dimensions. For instance, if X is defined as three-dimen-
sional, X(*) is interpreted as X(*,*,*). While this makes the use of
pointers convenient, one should be aware that, to a person unfamiliar
with the structure of a program's data, it obscures the actual opera-
tions that are taking place, e.g., example (5) above.
(2) The function DIM.F, when given a pointer as an argument,
returus as its value the number of words pointed to. This is extremely
useful !n programs that compute the values of array dimensions, as it
"sakes it unnecessary to save such values for later use. For example,
the folloving FOR loop uses the DIM.F function to determine its bounds:

FOR I-1 TO DIM.F(MATRIX(*,*)), FOR J-1 TO DIM.F(MATRIX(I,*)),


LEI MATRIX(I,J)- I**2 + J**2

Using the DIM.F function rather than constants or expzessions permits


the above &tateient to process ragged tables as well as rectangular
arrays.

2-09 COMPUTED TRANSFERS TO ALTERNA rVg STATE.AENT LABELS

The GO TO and IF statementL provide a facility for specifying a

The concept r.ion is presented in Secs. •6-to 2-18.


For present purpost.. can be tC-oug,-t of, and used, as a Lme-
dimeusional INTEGER variaoie.

t-..- - -.. - .
III
-67-
IIi
direct transfer of program control to a particular statement, or to
select, according to the truth or falsity of a logical axrression,
either of tvo alternaLo program branches.
Theme statements a:e frequently inadequate, however. For example,
there may be more than two alternative program paths to choose from,
or a program may have to be written to accommodate transfers to state-
ments that have not yet been written. Two new GO TO statements cir-
cumvent these problems.
If ve let LABELI, LABEL2, LABEL3, ... , LABELN represent statement
labels, and e represent an arithmetic expression, then a statement of
the form

GO TO LABEL1 OR LABEL2 OR ... OR LABELN PER e

evaluates e (rounding if it is REAL valued) and transfers program


control to LABELl if e=1, to LABEL2 if e=2, ... , to LABELN if e-n.
That is, the statement transfers control to the label in the first
label position, or the second label position, oz the nth label posi-
tion, according to the computed value of the expression e. Most
illegal transfers, e < 0 or e > n, are caught and cause program term-
ination.
Each of the names in the label list (other
+
than the first) must
be preceded by the word OR, or by a comma. The word TO is optional.
Typical computed GO TO statements are:

GO TO ACCOUNI.ONE OR PCCOUNT.TWO PER CUSTOMER


GO TO READ.AGAIN, WINDUP, CONTINUE OR HALT PER INSTRUCTION
GO TO Li, 27, 999, 12, 27, 13, 999 PER X"*2 + COUNT/N

In this last example note that the mame label name can appear in
more than one position in a label olit, and that label names can be
written without alphabetic characters.
When two distinct label names are used to identify the san
program statement, they are called equivalent labels. In the follo*-
ing examples the labels ADD and PLUS are used as distinct labels in
(I), and as equivalent labels in (2):

In this statement the vord AND cannot be ustd as a synonym for


coVM .
-68-

(1) 'ADD' ADD X TO COUNTER 'PLUS' LET X-X+1


(2) 'ADD' 'PLUS' ADD X TO COUNTER

When uaed with (l), the following GO TO statement transfers either


to the ADD or the LET statement; when used with (2), it transfers to
the ADD statevent regardless of the label selected:

GO TO ADD OR PLUS PER INDEX

Equivalent labels are useful when certain portions of a program


have been identified logically, but have not yet been written, or
when a program is written in such a manner that portions of it can
be included or removed without destroying the general orogram logic.
The following program segment illust:ates the use of equivalent labels
to indicate that sibsequent addittlons to the program will incorporate
certain changes that are not presently included:

READ STOCK.NUMBER, ITEMS


GO TO MEAT, POULTRY, GROCERY, SUNDRIES, DAIRY OR PRODUCE
PER STOCK.NUMBER/FACTOR
'MEAT '
'PCULTRY'
'GROCERY'
'SUNDRIES'
'DAIRY'
'PRODUCE'
SUBTRACT ITF4S FROM QUANTITY(STOCK.NUMBER)

As long as 1 < STOCK.NUMBER/FACTOR < 6, the GO TO statement always


transfers control to the SUBTRACT statement.
The following program illustrates another unA of a comruted GO TO
statement:

'.'5AD' READ X, Y, OPERATION


GO TO ADD. SUBTRACT. MULTIPLY OR DIVIDE PER
OPERATION
'ADO' LET ANSWER-X*Y GO TO PRINT
'SUBTRACT' LET ANSWER-X-Y GO 1O PRINT
'MULTIPLY' LET ANSWER-X*Y CA) TO PRINT
'DIVIDE' LET [email protected]
'PRINT' PRINT I LINE WITH , Y. A14D ANSWER AS FOLLOVS
***...e OP -o*.** . **o*.*....WiAT 115OP?

GO TO READ

Just as varief'.eu -r. be 9-,uDcrpte.A, to -an labels. For examplo,


it miltht '-e desirab'e t, ,.ae the si-te*er.t
-69-

READ I GO TO A(I)

rather than list all the possible label names in an ordinary computed
GO TO statement. The subscripted label GO TO statement form can be
used whenever this seems desirable. It is particularly useful in
programe containing GO TO statements that direct control to various
parts of a program when the program is frequently updated or augmerted.
Subscripted labels allow labels to be added or deleted witnout changing

"the GO TO statements that (may) pass control to tIem. The general

form of a subscripted label GO TO statement is

GO TO label (arithmetic expression)

As in other forms cf the GO TO statement, the word TO is optional.


When a subscripted GO TO statement is executed, control is trtnsferred
to the statement labeled with the same name and subscript 'ralue *qual

to the INTEGER value of the expression in the GO TO statement. If


this INTEGEP value h.as not been defined by a statement label, an un-
defined transfer may occur. For exzple, a program containing the
subscripted labels A(l). A(2), and A(3), and the statement GO TO A(1)
may transfer conticl to some indeterminate place if I is not equal to

1, 2, or 3. Most of tne ti"e illegal transfers will be dett. ted aad


progr=ms terminated.
A subscripted label is formel by adding a single subscr'pt to a
label r,a4w. Thus, the labels Al and A2 might be replaced by the labels

A(1) and A(2). Othar possible subacripted labels are:

NAME( ) SECTION.](1) PART(30)


THIS. IS.LABELtl SECTION.2(I ) A348(1")

While subscripted ]%bzls must be defined with integer constants


in their subscript positions, it is unnecessary for suticripts to
start with 1. or for them to be consecutive. LABEL(4) can be defined
vithout having LABEL()). LASIL(?), or LABEL(3) appear in the program.
Control. however, can only be transferred to subscripted labels that
have been define*d. The previous exsmple can be written us!ng sub-

scripted labels:
-70-

'READ' READ X, V AND OPERATION


GO TO OPERN(OPERATION)
'OPERN(1)' LET ANSWER-X+Y GO 70 PRINT
'OPERN (2)' LET ANSWER-X-Y GO TO PRINI
'OPERN(3)' LET ANSWER"X*Y GO TO PRINT
'OPERN (4)' LET ANSWER=X/Y
'PRINT' PRINT I LINE WITH X, Y AND ANSWER AS FOLLOWS
****.** OP **** ** **'** , WHAT IS OP?
GO TO READ

2-10 SOME LEVEL 1 PROBLEMS REVISITED

2-10-1 Problem 1-16-1--Finding the Average, Maximum,


and Minimum of a Set of Numbers
LET MAX = -99999.99999 LET MIN = -MAX READ N
FOR I a 1 TO N, DO READ X ADD X TO SUM
IF X IS GREATER THAN MAX, LET MAX = X REGARDLESS
IF X IS LESS THAN MIN, LET MIN - X REGARDLESS
LOOP
START NEW PAGE PRINT 3 LINES WITH N, SUM/N, MAX, MIN THUS
THE AVERAGE VALUE OF *** NUMBERS IS *
THE MAXIMUM VALUF IS *
THE MINIMUM VALUE IS ***.*
STOP END

2-10-2 Problem 1-16-2--A Prototype Accounting Syotem

PREAMBLE DEFINE ACCOUNT AS A 1-DIMENSIONAL ARRAY END


RESERVE ACCOUNT(*) AS 10 READ ACCOUNT
'READ' READ DOLLARS, CODEl, CODE2 IF DOLLARS EQUALS 0,
GO TO FINI
ELSE ADD 1 TO TRANSACTION.COUNTER ADD DOLLARS TO ACCOUNT(CODEI)
SUBTRACT DOLLARS FROM ACCOUNT CODE2) ADD DOLLARS TO ACCOUNT(6)
SUBTRACT DOLLARS FROM ACCOUNT 10) GO REAU
IFIN,' START NEW PAGE PRINT 1 LINE WITH TRANSAC, ION.COUNTER
AS FOLLOWS
***** TRANSACTIONS WERE PROCESSED THIS MONTH.
SKIP 5 oU'PUT LINES PRINT 9 LINES CONTAINING ACCOUNT(1), ACCOUNT(7),
ACCOUNT(2), ACCOUNT(8), ACCOUNT (3) ACCOUNT (4),
ACCOUNT(9), ACCOUNT(5), ACCOUNT(6), ACCOUNT (10) THUS
ASSETS LIABILITIES
CRRENT ASSETS CURRENT LIABILITIES
CASH ACCOUNTS PAYABLE $
RECEIVABLES * LOAN *
INVENTORY *
FIXED ASSETS *
PLANT * EQUITY
EQUIPMENT EQUITY *
TOTAL ASSETS $********* TOTAL LIABILITIES $*******
-7 1.-

SKIP 2 OUTPUT LINES PRINT 2 LINES WITH ACCOUNT(1) ACCOUNT(2), ACCOUNT(3),


ACCOUNT(4), ACCOUNT (5), ACCOUNT(6), ACCOUNT(7),
ACCOUNT(8), ACCOUNT(9), AND AC.COUNT(1O) AS FOLLOWS

STOP END

2-1o-3 Problem 1-16-5--A Pr 'grmn for Regression Anallysis

"A PROGRAM FOR REGRESSION ANALYSIS


READ N
FOR I = 1 TO N,
DO
READ X,Y ADD X TO SUMX ADD Y TO SUMY ADD X**2 TO SUMXX
ADD Y**2 TO SUMYY ADD X*Y TO SUMXY
LOOP
LET Al = ýN*SUMXY - SUMX*SUMY)/(N*SUMXX - SUMX**2)
LET AO = tSUMY - Al + SU1MX)/N
PRINT I LINE WITH 10 AND Al AS FOLLOWS
THE REGRESSION EQUATION IS Y * * X
STOP END

2-11 A NEW OUTPUT STATPEMNT

Many programming applications do not require the facilities of


the PRINT statement. A programmer is oftan satisfied with an econom-
ical means of displaying labeled values of selected variables with a
minimum of programaing effort; as lcg as oaLput is displayed neatly
and is well labeled, he is willing to cowpromise specialized report
formats for programning ease. This is particularly the case while
f
checking for errors, and in programs that are run for results and
not for formal management reports.
The LIST statement prints labeled values of expressions and
singly- and doubly-subscripted variables. The form of the statement is

LIST Ziat of arithr&tic expr'eseions aid array ncxwes as in


LIST X, MAN, DELTA + 3.5/C

Expression and array values are printed in standard formats.


Although they can be listed together in a single LIST statement, they
are printed separately; a LIST statement contasning a mixture of

t
Called "debugging" in the programming vernacular.

_____ _____ ____


-72-

different output types results in a report printed as if a new LIST


statement were written each time a type change is made. If X, Y, and
Z represent expressions or unsubscripted variables, NAME, GAME, and
PLACE singly-subscripted variables, and ROUTE, MATRIX, and TABLE
doubly-subscripted variables, then the statement

LIST X, Y, NAME, GAME, ROUTE, Z, TABLE, MATRIX, PLACE

has the same effect as the series of statements

LIST X, Y LIST NAME, GAME LIST ROUTE LIST Z


LIST TABLE, MATRIX LIST PLACE

As indicated in previous examples, individual subscripted variables


can be di3played, as well as entire arrays, by using different nota-
tions, e.g., X(5) ,ýnd X.t
Expreesian values are printed in rows across a page with the
"11name" of each expression above its value. As many values are put in
each row as fit, according to the spacing conventions. These conven-
tions allow 14 print positions for each value, with names right-
adjusted within the 14 positions. Values are right-adjusted beneath
their names. REAL values have the decimal point centered within t,,e
value field with 6 positions before and 6 after, and with 1 position
left for the sign. Two positions are always left between successive

fields across a page.


As an example of the LIST statement format for expressions, let
the following variables and their values be printed by the LIST
statement that follows:

INTEGER variables
N-5 MA--245 MOTORCAR-O KEY=1S6733578
NUMER.OF.JOBS. IN.QUEUE-45
REAL variables
TIM-345.87 LONGITUDE-37.37 PRICE-lO0.O0
TEMP.FAHRENHEIT-267.66 RATE-545.6667
RATIO-O.0

+
In this statement corrections are not made for missing stubscripts
(see Sec. 3-2'); X is treated as an array name and not as an improperly
specified element X(1).
-73-

Program statement
LIST N/MAN,MOTORCARTIMELONGITUDE,NLNBER.OF.JOBS.IN.QUEUE,
TEM. FAHRENHEIT,PRICE+RATE,KEY,RATIO
Program output
N/MAN MOTORCAR TII. LONGITUDE
0.024081 0 345.870000 37.370000
NUMBER.OF.JOBS TEMP.FAHRENHEI PRICE+RA'E KEY
45 267.660000 -445.666700 156733578
RATIO
0.000000
These values, of course, are printed out differently on a printer with
a wider width of paper.
Singly-aubscripted variab•e• are printed in colums following the
same heading and spacing conventions as expressions. The length of
each column is determined by the number of elements in the array, the
longest array determining the maximum number of rows printed. Vari-
ables with fewer elements than the maximum show blanks in the positions
where no elements appear. For example, if a RESERVE statement reads

RESERVE N AS 10, MAN AS 5, MOTORCAR AS 7 AND TIME AS 4

and a LIST statement is written

LIST N, MAN, MOTORCAR AND TIME

the following columns are printed (note that the left-hand margin is
numbered to identify the element values):

N MAN MOTORCAR TIME


1 5 245 0 267.660000
2 4 18 1 268.870000
3 3 99 1 288.000000
4 2 8894 0 302.473215
5 1 4 1
6 0 0
7 -1 1
8 -2
9 -3
10 -4

.. t both rectangular and ragged, are


printed in rows and coluainv acros,& and cd-vn a page, with the rows and
colums numbered the sem as the columns of the singly-subscripted
variables. The heading convention places the, array name above the
-74-

first column of element values; the spacing conventions are the same.
If more than one array is mentioned in a LIST statement, they are
printed successively in the order in which they are listed. For
example, if TABLE is an array defined by the statement

RESERVE TABLE AS 5 BY 4

it is printed as follows if it is INTEGER:

TABLE
1 2 3 4
1 0 556 90 78
2 24 88 8 5555
3 5 0 777 89
4 337 7 0 98
5 0 55 54 0

or as follows if it is REAL:

TABLE
1 2 3 4
1 0.000CO0 556.000000 90.000000 78.000000
2 24.000000 88.000000 8.000000 5555.000000
3 5.000000 0.000000 777.000000 89.000000
4 337.000000 1.000000 0.000000 98.000000
5 0.000000 55.000000 54.000000 0.000000

Arrays with more columns than a page can contain are continued
on successive pAges. For example, if TABLE had been reserved as
5 BY 7, an additional page would be printed as follows:

TABLE
5 6 7
1 12 28 1000
2 301 -100 27
3 0 0 0
4 16 0 -16
5 -3 3 4

As the spacing conventiotis allow only six figures before and


after a decimal point, an output of very large and very smIa numbers
cannot be executed through the standard LIST forlmt. Numbers treater
than 99999Q.999999 or smaller than 0.000001 are printed in a scaled
scientifi: notation format instead. As an example. assume that the

Scientific notation prints a number in the form of a decimal


-75-

variables X, MAN, and AVERAGE are to be printed by the statement


LIST X, MAN AND AVERAGE, and that the value of MAN is 13,700,000,000.
The following line will be printed:

X MAN AVERAGE
23.111100 1.370000E+10 9,252525

The LIST statement, unfortunately, can be misleading in one


respect - that of significant figures. As a digital computer is a
finite-word-length calculating machine, it can retain only a limited
number of figures in its internal (alculations; generally, the pre-
cisi on of computations is limited to eight or nine significant figuras.
Computations are subject to error, therefore, as when two 10-decimal-
place fractions are added. Thus, there can be some danger in inter-
preting the twelve allowable decimal figures printed by the LIST
statement as "true values." The same rules of careful error analysis
that apply to other output to determine the significance of printed
values should apply to LIST output.

2-12 MORE ON LOGICAL EXPRESSIONS

Thus far, logical expressions have been used to compare arithmetic


quantities: a logical expression is true if the relationship it ex-
presses is true, false if the relationship does not hold. Often, how-
ever, there is a need for logical expressions employing nonarithmetic
comparisons. This section describes two applications of a logical
expression using "property" relationships.
(1) As each arithmetic expression has a numerical value that is
either positive, negative, or zero, an arithmetic expression can be
compared with one of the property names POSITIVE, NEGATIVE, or ZERO,
and a true or false condition set. This condition can then be useA
to direct the flow of program logic. The form of the logical

number between zero and ten scaled by a power of ten; 10.6 is printed
"a 1.06(10#'+1). 0.00123 as 1.23(10"-3). 546372.3 as 5.4637?3(10O.5),
etc. The power of ten, e.g., +1. -3, +5, indicates the direction and
distance in which the decimal point must be moved to convert the
fraction to the true number.
-76-

expression is

arithmetic expression IS property nane or


arithmetic expression IS NOT property nme

The following program statements are permissible:

IF VALUE(ITEM) IS ZERO, GO TO NEW.ITEM OTHERWISE


IF Y**2+X**2 IS POSITIVE, GO TO ROOT ELSE
IF SUM IS NOT ZERO, GO TO NEW.STEP OTHERWISE

The words POSITIVE, NEGATIVE, and ZERO are recognized in their correct
context as property names when they follow the word IS or words IS NOT
in a logical expression. Therefore, they can be used without reserva-
tion as variable names or labels. In fact, if POSITIVE is declared
as a variable, the SIMSCRIPT II compiler has no difficulty with the
statement

IF POSITIVE IS NEGATIVE, ........... ELSE

(2) Properties of certain special names can be used in logical


tests. These names are automatically defined and their values changed
during the course of computation. Section 2-73 describes these words,
their property names, and how they are used.

2-13 SYSTEM-DUFINED VALUES

Prograimers often use input data to control the flow of informa-


tion within a program. Such statements as

READ N GO TO LABELA OR LABELB OR LABELC PER N and


READ N IF N EQUALS 0, GO TO FINISH OTHERWISE ....

are typical and have been used in several example problems.


SIMSCMdPT 11 offers a programmer several system-defined names
that allow him to look at a number of properties of input data .o.".rv
they are read from cards by a free-form READ statement. Vhen a pro-
gramer uses any of these names, the SIMSCRIPT II system automatically
determines a property based upon the current input data status. The
programewr is then free to use this property valu# as he wishes. The
system-defines naes are:
-77-

Name Value

SFIELD.F Starting column number of the next data field


EFIELD.F Ending column number of the next data field
MODE Mode of the next data field: either INTEGER or REAL
CARD First data field on card indicator; either NEW card
or NOT NEW
DATA No data items in data deck indicator; either ENDED or
NOT ENDED

Some examples Illustrate the use of these system variables.


(1) The use of SFIELD.F: A deck of punched cards contains data
punched in two different formats. Some of the cards have data punched
beginning in column 1, while other cards are punched starting in
column 25. A group of statements labeled '1' processes the cards with
their data beginning in column 1, and a group of statements labeled
'25' processes the other data cards. A value for SFIELD.F is deter-
mined before each new value is read, but the dat& item itself is not
read until a READ statement I- executed.

'LOOK' IF SFIELD.F EQUALS 25. GO TO '25' ELSE


'1' READ X ADD X TO SUMX GO TO LOOK
'25' READ Y ADD Y TO SLIMY GO TO LOOK

(2) The use of EFIELD.F: N integers are punched on data cards


when we want to count the number of one-digit numbers, the number of
two-digit numbers, ... , or the number of ten-digit numbers in the
data deck.

PREAMBLE
DEFINE COUNT AS AN INTEGER, I-DIMENSIONAL ARRAY
END
RESERVE COUNT(*) AS 10
FOR I -01 TO N. DO THE FOLLOWING
ADO I COUNT(EFIELD.F-SFIELD.F+I) SKIP 1 FIELD " TO THE
" NEXT NLMBER
REPEAT

A three-digit number, such as 274, in columns 12, 33, and 34 will


have EFIELD.F - 34. SFIELD.F - 32, and will cause COUNT(34-32*1)
COUNT(3) to be incremented.
(3) The use of ,ODE: To search through a neries -f numbers om
-78-

cards and add together all the integers (n,. whole numbers, hut num-
bere without deciral points).

FOR I - I TO N, DO IF M'ODE IS INTEGER, READ NUMBER


ADD NUMBER TO SUM
GO TO LOOP
OTHERWISE SKIP I FIELD
'LOOP' LOOP

(4) The use of CARD: Although SIMSCRIPT II ignores card columns


or card numbers when reading data, a programmer may want to know if
he is at the beginning of a data card. Perhaps he wants to print a
count of the number of data cards read at different stages of a program.

'LOOP' IF CARD IS NEW, ADD I TO COUNT "ADD ONLY ON A NEW CARD


OTHERWISE

(5) The use of DATA: A programmer may want to know if he is


out of data without the necessity of adding a duimy data card and
testing for 0 or some other value. He cat, do this by testing to see
if the next data item to be read exists.

'READ' READ X

• ) perform computations in here


IF DATA IS ENDED, STOP
ELSE GO READ

When there are no data, e.g., all data have been read and look-
ahead is impossible, tha system variables have these values:

Nane value
SFIELD.F 0
EFIELD.F 0
MODE ALPHA
CARD NEW
DATA ENDED

h-14 5YS_7W5-FTNED CCM•SAVT3

Scientific and engineering calculations often involve etanmard


scientific constants; mathmatical computations often require values
of numrical constant.. Numbers such as v - 3.14159 ......... and
* - 2.718 ........ are two well-known and often-used constants.
-79-

SIMSCRIPT II maintains a library of standard values. When the


name of a library constant is used in a SIMSCRIPT II program, the
correct numerical value of the constant is inserted in its place.
These constants may be used wherever a "regular" numerical constant
can be used.
Library constants have names that look like variable names except
that they end in .C. This is another reason why variable names should
not end with a letter preceded by a decimal point.
The library constants and their values are listed in Table 2-3.

Table 2-3

SYSTEM-DEFINED CONSTANTS

Standard
Name Symbol VWlue Units Mode

PI.C w 3.14159265 -- REAL


EXP.C e 2.718281828 REAL
INF.C - "argast value -- INTEGER
RINF.C computer can store -- REAL
RADIAN.C - 57.29577 degrees/radian REAL

2-16 THE S7RUCTYjRE Or A SI%5CR rPT i PROGRAM

Problem solutions often require sequences of similar or identical


statements to appear at different placen in a program. Although ttesý,
statements can be rewritten each time they are needed, it ic fer more
convenient to combine them into groups and call on them by symbolic
names.
Labeled groups of statems'nts that car, be called on by naw are
called bp.r•vgrcm. ilThy are distinguished as programs beitse thwy
do som* specfiL task; they are called subprograms because they do
not have an independent existence, but are controlled by other prt-
gram. A subprogram is •;2 v rather than executed in sequs-nce as
are the statements READ. LET. and RESERVE. When a subprogron !s
called, control passes from a "•:-•i program to the st~bpicgram, along
with instructioms for returning control to the call'nf pry gram. A
-80-

subprogram can call upon other subprograms; it can be both a called


and a calling program coincidentally.
Since subprograms cannot be executed directly but must bi called,
at least one nonsubprogram is required in every program deck. Every
SI?1SCRIPT II program mnust contain such a program, called a main Prora,
&id nmy contain one or more subprograms. When a program deck is com-
piled and loaded into memory for execution, the execution begins at
the firit instruction in the main program and proceeds from there, as
the logic of the main program-subprogram package commands. All of
the example programs used thus far have been main programs. In suc-
ceeding sections we will describe the structure and use of subprograms,
and transcribe some of the main program examples into a subprogram
framework.
Figure 2-8 shows three examples of main program-subprogram organ-
izations. The examples in Fig. 2-8 consist of a main program and one
or more subprograms, with arrows indicating the direction of program
flow. An arrow pointing to a subprogram indicates a call on that
subprogram, and an arrow pointing oppositely means a return to a call-
ing program.

MAIN PROGRAM

o
0
0
o0 = 1

o I.
toL iGR11
0

Fig. ?-Si -- Program consistiný of a subpregram


called by a main program

In Fig. 2-01a the p:igrsa


SAinf calls an rho subprogtam in tvo
places. in each inattnce, after executing Its statse~mnts. the sub-
program returrs control to the main program &t the statement follov-
ing the one that called it.
-81-

MAIN PROGRAM

SUBPROGRAM 1
0
O

SUBPROGRAM 2

o0
O _______ SUBPROGRAM 1

END

Fig. 2-8b -- Program consisting of two subprograms


called by a main program

MAIN PROGRAM

0
SUBPROGRAM I1UBPROGRAM,

0
0-
0 SUPRORAMSUBPROGRAMTI
0 _____ UBRGA 2
.3__

0
END

Fig. 2-8c -- Program consisting of three subprograms


* and a main program

Figure 2-6b shows a slightly more complicated program composed


of a main program and two subprograms. The main program calls on
each of the subprograms; they are independent of each other.
Figure 2-8c illustrates a more complex situation in which a
-82-

main program and three subprograms interact. Subprograms 1 and 2 are


both called aid calling programs -- they are called by the main pro-
gram and, in turn, they call on Subprogram 3. The call of Subprogram
I or 2 by the aain program is the first Zevel of calling; the call of
Subprogram 3 by Subprograms 1 and 2 while under the control of the
main program is a second level. In general, there can be any level
of calling in effect within a program at any time. The calling rules
do not change from level to level -- control always passes from a
calling to a called program and back again. Whether there are many
intermediate calls and returns between an original call on a subprogram
and a return to its calling program is insignificant. If A calls B
and B calls C, then C must return control to B before B can retu:n
to A. A subprogzam cannot return control to any routine other than
the one that called it, e.g., C zannot return directly to A.
Subprograms are like obedient servants. They can be called upon
to do a job, and they always repoit back when they are finished. The
fact that tLe servants may in turn have servants in no wdy complicates
the rules.

2-16 SUBPROGRAM DEFINITION

As a SIMSCRIPT II program can be composed of a main program artn


a number of more jr less independeat 3ubprograms, statements are needed
to inform the compiler of the overall program structure and enclose
the statements belonging to individual subprograms.
The main program in a program deck should be precedei by the
statement

MAIN
although this is not always necessary. Since all other sections of
a program deck must have a heading, It is possible to make MAIN
optional and assume a program is a main program if it is not other-
wise labeled. Nevertheiess, it ic good programming practice to label
programs fully. From now on, we shall do so.
A subprogrcm definition statement precedes each subprogram and
(1) declares that the statements following are part of a subprogram;
-83-

(2) bestows a name to the subprogram; and (3) sets up a communication


mechanism for trdnsmitting data between the subprogram and programs
calling it.
Each subprogram has a name that is used to call it. This name
is declared in the subprogram definition statement that precedes the
statements composing the bodyj of the eubprogramn. Subprograms follow
the same naming conventions as variables (see Sec. 2-00). Each vari-
able and subprogram name must be unique.
A subprogram definition statement has the form

ROUTINE rxne

The optional words TO and FOR are allowed after the word ROUTINE to
make statements more grammatical. Thus, a program that extracts
square roots might be called SQUARE.ROOT and could be defined by the
statement

ROUTINE SQUARE.ROOT

or it might be called TAKE.SQUARE.ROOT, and De defined by the statement

ROUTINE TO TAKE.SQUARE.ROOT

or the original name might be preferred and be used in the statement

ROUTINE FOR SQUARE.ROOT

As the words TO and FOR are optional, care must be exerzised to avoid
using the short form of the statement when defining a subprogram
named FOR or TO. If this is done, the compiler will continue to look
for a subprogram name after it sees the words TO or FOR, and mistakenly
use the next word it sees. For example, if a subprogram named FOR
is defined by the statements

ROUTINE FOR
LET X = 1
END

the compiler assumes that the subprogram definition statement is


ROUTINE FOR LET, misnames the routine, and leaves an incomplete state-
ment X=1 to deal with next. The proper use of a subprogram definition
statement with subprograms named FOR or TO should include the follow-
ing optional, although ungrammatical, words:

I-
-84-

ROUTINE FOR FOR ROUTINE TO FOR


ROUTINE FOR TO ROUTINE TO TO

Each subprogram is bracketed by a ROUTINE statement and an END


statement. The statements between them constitute the body of the
subprogram and are executed when the subprogram is called. The word
routine will be u3ed from here on to refer to subprograms.
Routines are generally used to process data. In a square root
routine, a number is an input to the routine, and the value of the
square root of the number is an output of the routine. Data are
passed from calling to called programs and back again in two ways:
implicitly, as values of global variables, and explicitly, through
arguments in an argwnent list.
A global variable is a variable whose name has a common meaning
throughout a program; every use of the name of a global variable
references the same memory location (and hence, the same data value)
regardless of the routine in which it appears. A variable is only
defined as global when it appears in a DEFINE statement in the
prem•mble. Therefore, certain variable names must be put in DEFINE
statements in order to declare them as global even though their pro-
perties are fully described by preceding NORMALLY statements. In
such cases the DEFINE statement can be used without any properties,
as in

DEFINE MAN, X, TIGER AND VECTOR.SUM AS VARIABLES

A local variable, on the other hand, has its value defined only
within a particular routine. The same name can be used for a local
variable in many routines; when it is so used it refers to a different
quantity in each routine, as if a different variable name were being
used in each place. Local vs lables can be used mnemonicaliy in dif-
ferent routines without the various applications interfering with one
another. When a name is defined within a routine, it is unique to
that routine and does not conflict with other uses of the same name.
Thus, it Is possible to have many different elements with the same

t
" See p. 90.
-85-

name -- variables and labels - in a program. Furthermore, local


variables are not always present in memory, as are global variable-;,
but pass in and out of existence as the routines in which they appear
are called. This dynamic quality conserves memory space, and it is
important in programs having a large number of local variables and
routine calls.
The preamble is used to define global variables. Any variable
not named in a program's preamble is local to whatever subprograms
it is used in. Names declared as global can be temporarily defined
as local within particular subprograms by using their names in DEFINE
statements within the routines. Local variables have the properties
of the background (NORMALLY) conditions in effect at the time they
are first encountered, unless they are otherwise defined through
DEFINE statements.
The following program implicitly spec'fies that X and Y, which
are not mentioned in the preamble but which do appear in the routines
RTN1 and RTN2, are INTEGER , unsubscripted local variables. The
names X and Y refer to different quantities in RTN1 and RTN2.

?REAMBLE
NORMALLY, MODE IS INTEGER, DIMENSION=2
DEFINE GHOST AND SPECTER AS REAL ARRAYS • Program Preamble
DEFINE VALUE AS A REAL, I-DIMENSIONAL ARRAY )
NORMALLY, DIMENSION= 0
END
MAIN
This section is the main routine. It can contain
references to both global and local variables.
END
ROUTINE RTNI
IThis section contains statements that use the
variables X and Y.
END
ROUTINE RTN2
This section contains statements that use the
variables X and Y_
END

All variables that do not appear in a program preamble are local.


Local variables can be used both in routines and in main programs.
-86-

Local variables that have different properties from those of the


current NORMALLY conditions are declared by DEFINE stateminte in their
respective routines. NORMALLY statements can be used in routines to
set background conditions for local variables, but these conditions
do not carry over from one routine to another. Only the last defined
NORMALLY conditions in the preamble carry over from routine to routine.
A main program can have local variables declared in DEFINE statements
that follow the statement MAIN. The example below illustrates hov
NORMALLY and DEFINE statements are used to specify properties of
local and global variables.

PREAMBLE
NORMALLY, MODE IS INTEGER
DEFINE VI AND V2 AS REAL, 1-DIMENSIONAL ARRAYS Program
DEFINE V3, V4 AND V5 AS 2-DIMENSIONAL ARRAYS Preamble
NORMALLY. MODE- REAL
END

MAIN READ N RESERVE V1,V2 AS N, V3,V4,V5 AS N BY N


READ VI AND V2 LET V3(1,1),V1(V2(1))
and other statements that make up a main program,
including call statement. for the following routines

END "OF MAIN ROUTINE''

ROUTINE TO PROCESS.DATA
NORMALLY, DIMENSION- 1, MODE IS REAL
DEFINE Z AS AN INTEGER ARRAY
DEFINE L. M AND N AS INTEGER VARIABLES
RESERVE Z AS 10
'START'

GO TO START
and other statements that make up a routine

END ''OF ROUTINE PROCESS.DATA


-87-

ROUTINE FOR PRINTING


DEFINE Z AS A 2-DIMENSIONAL VARIABLF
RESERVE Z AS 10 BY 5
'START'

END ''OF ROUTINE PRINTING

Some points to observe from this example are:


(1) A preamble can have more than one NORMALLY statement. Each
successive NORMALLY statement sets background conditions that hold
until they are overridden. The last NORMALLY conditions hold for all
undefined local variables in routines. Local variables in routines
can have their properties defined by NORMALLY and DEFINE statements
in the routines.
(2) The order of NORMALLY and DEFINE statements is always impor-
tant. In the above routine PROCESS.DATA the variable Z is defined as
an INTEGER, 1-DIMENSIONAL array by the NORMALLY and DEFINE statements.
If these statements are reversed, the NORMALLY conditions of the pro-
gram preamble will apply to Z and it will be defined as an unsubscripted
variable, a definition that subsequently will be contradicted by the
RESERVE statement, although this need not always be true. The order
of definition statements is always important.
(3)
Unsubscripted local variables (L, M, and N in PROCESS.DATA)
are automatically assigned storage locitions and initialized to zero
when a routine is called. They are returned to "free storage" when
control passes back from a routine to a calling program. Subscripted
local variables are not automatically assigned storage locations, and
must be RESERVED before they can be used. When an array is RESERVED,
its elements are automatically initialized to zero.
(4) Local variables can have conflicting definitions in different
routines without any difficulty, as Z is a 1-DIMENSIONALINTEGFR local
array :n routine PROCESS.DATA and a 2-DIMENSIONAL,REAL array in routine
PRINTING. If Z were used in the main program, it would be local to
it, defined as unsubscripted, and REAL.
(5) Labels are always local. When a name is used as a label it
references a program statement in the routine containing the label.
-88-

Label names can be duplicated in different routines without conflict.


Labels appearing in one routine are not defined within other routines,
and transfers cannot be made between routines by means of GO TO
statements.
(6) A subscripted local variable that does not appear in a
DEFINE statement within a routine has its dimensionality defined by
its first use, i.e., even if a routine's NORMALLY condition is 0-
dimensional, the statement LET X(I)zO defines X as 1-dimensional.
(7) The concept of a routine preamble is a convenient fiction.
Definitional statements placed at the head of a routine are not pre-
ceded by PREAM8LE and followed by END, as are similar statements in
a program preamble. NORMALLY and DEFINE statements can be ased any-
where within a routine.

2-17 ROUTINES USED AS FUNCTIONS

A function is a routine that yields a single value when applied


to a set of data. The value given is known as the result of the
function. The familiar symbols sin (y) and Vx represent the mathe-
matical functions sine and square root, i.e., they represent procedures
for computing the value of the sine of y and the square root; of x.
When a function is used in an -xpression, there is no intent to
substitute the literal symbol of the function in the expression but
only the number that results from applying the function to its
(input values).
mrgawne•t The functicon symbol represents a procedure
for converting the value of an argument or arguments to a new value,
called the value of the function. We pretend that this valle iS

assigned to the function symbol and use it in subsequent calculatione.


Thus y -- ,x means "compute the value of the square root of E and
assign it to the variable y."
Functions are so basic to computing that they must be incorpo-
rated into the rules for evaluating arithmetic expressions:
o Arithmetic expressions are composed of variables, con-
stants, functions, arithmetic operators, and parentheses.
o Expressions are evaluated according to the parentheoes
and operator hierarchy precedence rules; functions ore
-89-

evaluated by application of the parentheses rule (see


Sec. 1-03, p. 2, and Sec. 2-04, p. 40).
The following two examples illustrate the rules for evaluating
expressions that contain functions:

Expz'ession: X*Y+SQRT.F(P+Q**2/M); SQRT.F is a function that


takes the square root of a single argument enclosed
in parentheses.
Eval•ation: (1) Application of the parentheses rule evali-tes,
from left to right, all terms containing parentheses.
A value is first computed for the expression P+Q**2/M.
In this intermediate computation, Q*2 is evaluated,
the result divided by M, and this result added to P.
This value is then used as the argument of the square
root function, which is called, and produces the
result a.
(2) The expression X*Y+s is evaluated by applying
the operator precedence rules; X and Y are multiplied,
and S is added to their product.

Expreasion: SQRT.F((X(I+1)**2+Y(J)**2)+(5.5*Z(2*I+J)-I)).
Evaluation: (1) Application of the parentheses and overator pre-
cedence rules evaluate, in turn, the sub-expressions:
(a) 1+1 - a (b) J - d (c) b**2 - c
X(a) - b Y(d) - • e**2 - f
c+f - g
(d) 2*1 - h (e) g+- - n (f) SQRT,.F(n) * p
h4+J - i
Z(i) jj
5.5*j - k
k-l m

An important rule to remember is that expressions are evaluated


term by term, with the parentheses rule being invoked within terms
whenever parentheses are ,-ied. In the event of consecutive paren-
thesei, the most deeply imbedded parentheses are evaluated first.
Whenever an expression enclosed within parentheses consists of more
than one tern, the operator precedence rules are applied to determine
the order of evaluatioit. Functions with argument lists and subscripted
variables are alwave evaluated under the parentheses rule. The follow-
ing example illustrates the invocation of the parentheses rule to
evaluate a complicated expression containing a function call and con-
secutive parentheses:
-90-

Expre.aaion: 5.0 + (SQRJ.F(I) + ((A+B)/C) + D)


Evaluation: (1) SQRT.F(J) -* a
(2) A+B * b
b!C * c
(+D- a
&,)
(4) result- 5.0+e

Arguint. are valuss that are transmitted from a calling to a


called progrm. They represent variables that are local to a routine
and that receive initial values when a routine is called. When a
routine is written (described in Sec. 2-19), local variables that are
arguments of the routine are formaZ place-holders; they serve as
receptacles into which values are dropped when a routine is called.
When a routine is called (also described in Sec. 2-19), actual values
are put in the positions in which the formal arguments appear in the
routine definition and these values are transmitted to the routine
and used to initialize the routine arguments.

2-18 L.BR4MR FUNCTIO'.S

Some functioa.v are used so frequently that they are incorporated


in the SISCfIlT II system. These functions are described in Table 2.4.
Each library function, with the exception of MAX.F and MIN.F,
has a fixed number of arguments. The library functions can be used
freely in all computations, although values, of course, cannot be
assigned to them. Nunction arguments can be arithmetic expressions
of any complexity (including function name) as long as they are of
the correct mode and their values do not exceed any restrictions they
my have (see Table 2-4). Some examples of the use of library func-
tions are:
-91-

Table 2-4

SIMSCRI"PT II LIBRARY FUNCTIONS

Nm Arumentsu Operation Function odeestrict.ion

S.Ft a if 0 mode of at-SuetIt none

. Ft alp* 2,...aa value of largest INTEGER if all argmenta INTEGER non


argummnt RAL if one ergmnt REAL
KIN.Ft e6.129...10n value of smallest INTEGER if all argument INTEGER none
arglument REAL if one argument REAL
MDO.Ft alo2 1e-TR.NC F(e 1/e 2 )*e, 2 INTEGER if all argiuments INTEGER (o2 0
REAL if one argument REAL
DIV.FM else2 TRUNC.F(e 1 /a 2 ) INTEGER n d1 *2 INTEGEP,

INT.Ft value of o rounded INTEGER ne


to &a intager
REAL.Ft value of * expressed REAL none
as a decimal number

FRAC.F a fractional part of REAL e moat be REAL


a; *-TRtU¢J.F(e)
TRUNC.F 0 integer part of INTEGER a miut be REAL
a; e-FRAC.F(e)

SIGN.F 1if a O 0 INTEGER none


0 if a - 0
-1 if o < 0
SFIELD.F am* wee Sec. S-13 INTEGER free-form input
only
EFIELD.F noe cee Sec. 2-23 INTEGER free-form input
only
DIM.F v nuter -,i elements INTEGER v a pointer
in array poioted to
SQRT. F .- REAL - 0and REAL
EXP.F a exp(e) - EXP.C**e REAL a went be REAL

LOG.E.F a loe(e) REAL a > 0 nd REAL

LOG.10.F a 1o61 0 (s) REAL a > 0 and REAL


SIN.F e sin(e) REAL a PM and *x-
pressed in radians
COS.F a cos(e) REAL a REAL and ex-
pressed in radians
TAM.F ton(*) REAL REAL and ax-
pressed in radians
ANESN.F a arcein(e) REAL -1 1 o 1 1 and
REA
ARCCOS.F 0 .rccos(s) REAL -1 < * . 1 and
REAL
ARCTAN.F @1 oe2 arctan(e 1 /e 2 ) REAL (a 1 .o 2 ) 4 (0,0)

_ I I_ I
tDenotes a function compiled in-line rather than called esa routine.
and REAL
-92-

Statement 11 Action

(a) LET Z:SQRT.F(X**2+Y**2) x2 +¥ 2

(b) ADD SQRT.F(SQRI.F(N)) TO SUM SUM + N


(c) LET MAX:ABS.F(X(1))
FOR I= 2 TO N,
LET MAX=MAX.F(ABS.F(X(I)),MAX) finds MAXIXIJ
(d) LET VAR=MEAN*LOG.E.F(RANDOM) mean [ln(random))
(e) LET DECIMAL:MOD.F(X,I) fractional part of X
(f) FOR I=1 TO ABSF(N-K), LET X(I1): initializes array X
(g) FOR J=1 TO DIM.F(TABLE(*)),LET TABLE(J)=O ziroes array TABLE

2-19 PROGRAM-DEFINED FUNCTIONS

Routines that perform as functions can be defined. Computations


are programmed in the routine, and the routine name is used to repre-
sent the function. Library and program defined functions are used in
exactly the same way.
Routines used as functions can be defined with or without argu-
ments. Alternate forms of the ROUTINE statement are indicated below.

(a) ROUTINE nane


(b) ROUTINE nane (argunent 7-st)
(c) ROUTINE nae GIVEN argument list

Routines can be defined without arguments, as in (a), when all


input values are transmitted to the routine through global variables.
When argume-..ts are used, they are names of local variables in the
body of a routine. When a function is called, the values of eYpres-
sions used it the argument list are transferred to the routine. In
the routine SQRT, for example, defined by the statement ROUTINE FOR
SQRT(N), N is a local variable appearing in the computational procedure
for computing a square root. When the function SQRT is used in a
program, it can be written as SQRT(4), or SQRT(VALUE*SUM-1) or
SQRT(SQRT(Z**3)), with an arithmetic expression replacing the iden-
tifier of the argument list.
As illustrated in Sec. 2-16, the optional words TO and FOR can
be used between the word ROUTINE and a subprogram name. In the long
form of the ROUTINE statement with arguments, the word GIVEN can be
-93-

replaced by the words GIVING, THE, or THIS to make declara'ions more


readable. These options make a large number of ROUTINE statement
forms possible. For example:

ROUTINE ALLOCATE
ROUTINE TO ADD(X AND Yi
ROUTINE FOR ADDING GIVEN X ANU Y
ROUTINE LOG(X,Y)
ROUTINE FOR ALLOCATING THIS MAN

When a routine with arguments is called as a function, however, it


can only be called as

name (ar-z-tnet~c e

Only a ",", not an AND or ,AND can be used to separate expressions in


a function call.
A routine used as a function returns a value tu thp calling pro-
gram when it executes a RETURN statement. This Rtatement is written as

RETURN WITH arithmetric expression or


RETURN (arithmetic expression)

The value of the expression is computed before tne routine returns to


the calling program. The computed value is returned in the mode of
the function, specified in the program preamble in a function mode
definition statement.
The DEFINE statement used to declare the mode of a functiona in a
program preamble is of the form:

DEFINE name AS mode FUNCTION

where the words AN INTEGER or A REAL are optional and can be substi-
tuted for the mode when appropriate. More than one function can be
declared in a single DEFINE statement, as, for example, in the statement

DEFINE ROOT, ALLOCATE AND COMPLEX.ADD AS REAL FUNCTIONS

Each function must be defined in the prograw preanble in order to


distinguish it from a variable in subsequent subprograms.
There can be more than one RETURN statement in a routine, for a
routine ay be used for multiple purposes and have multiple exit
points, each of which returns a different value. All function values
I
-94-

are returned in the same mode, of course. The program shown below
illustrates the use of arguments and the ROUTINE and RETURN state-
meats. The routine computes the 2n-th root of an input value, where
n can take on the values 1, 2, or 3.
In the program preamble:

DEFINE ROOT AS A REAL FUNCTION


Routine definition:

ROUTINE FOR ROOT (N,X)


IF N - 1, RETURN WITH SQRT.F(X) ELSE
IF N - 2, RETURN WITH SQRT.F(SQRT.F(X)) ELSE
IF N a 3, RETURN WITH SQRT.FýSQRT.F(SQRT.F(X))) ELSE
RETURN WITH -1 "WHICH IS AN ERROR MESSAGE CODE
END ''ROOT ROUTINE"

Routine used in other programs:

LET Y -ROOT(2, LIST(ROW,COLUMN))


ADD ROOT(MX**2+V*WEIGHT/MASS) TO VAR
LET I=MAX.VF(09ROOT(KQ))
In the last example, I is set equal to 0 if K is not 1, 2, or 3;
otherwise, it is set equal to the appropriate root of Q.
Notice that the arguments of ROOT are used in its body as decision
or computing variables. When the routine ROOT is called, the expres-
sions that appe&r in the positions of N and X are evaluated and set
as the initial values of N and X in this call. Thus, unlike other !
variables that are initialized to zero when a routine is called,
routine arguments are iaiitialized to values specified in the state-
ments that call them.
Routine arguments, unless define', have their mode implied by
the background conditione in effect when the routine is compiled.
In a large program with se%.ral routines, it is likely that many
routine arguments will have different mode specifications. Most of
these will be made through DEFINE statements, as they will not agree
with the NORMALLY conditions. The properties of the remainder will
be specified by implication. The routines that contain DEFINE state-
ments will be definitionally self-contained; the others will be de-
fined in the context of the program preamble,
-95-

Consider the following routine:

ROUTINE FOR ILLUSTRATION(X,YZ,I)


DEFINE X, Y AND Z AS REAL VARIABLES
DEFINE I AS AN INTEGER VARIABLE

END

This routine can be written without one of the DEFINE statements,


depending on the NORMALLY conditions of the program preamble. It is
written as shown above to ensure that the routine will not be altered
no matter how the preamble is changed.
Arguments in statements that call a routine must match the argu-
ments of the defined routine in mode. Routine ILLUSTRATION above can
be called as ILLUSTRATION(1.0,2.0,O.5,1), but not as ILLUSTRATION-
(1,2.0,0.5,1). Mode conversions are not made automatically as they
are in "mixed mode" expressicns.
The number of arguments in a routine, like the number of sub-
scripts in a subIcripted variable, is fixed. If a routine appears
in different places in a program with a varying number of arguments,
standard corrective rules are applied.
The "correct" nunber of arguments for a routine can be declared
in the DEFINE statement that defines its mode. For this use the
DEFINE statement has either of the phrases

GIVEN i ARGUMENTS or GIVEN I ARGUMENT

added to it, as in the declarations

DEFINE SQRT AS A REAL FUNCTION GIVEN 1 ARGUMENT

and

DEFINE VALUE AS AN INTEGER FUNCTION WITH 3 ARGUMENTS

The words WITH or GIVING can be substituted for GIVEN as desired.


The words ARGUMENT and its synonym, VALUE, are optional. Usually
there is no difference between the number of arguments defined and
the number used, and the correct number is the number found in all
statements. But if, either inadvertently or by design, the number
of arguments varies, the following rules are applied:
-96-

(a) If fewer arguments are listed than are correct, the missing
arguments are assumed to be zero and a warning message issued. Thus,
a routine that has been defined as

PREAMBLE
DEFINE SUM AS A REAL FUNCTION WITH 1 ARGUMENT
END
ROUTINE TO SUM(N)
DEFINE N AS AN INTEGER VARIABLE
FOR I = 1 TO N, ADD 1/I TO X
RETURN(X)
END

when used in a subsequent statement as

LET ANSWER=COUNT+TOTAL+SUM

will be compiled as though it were written

LET ANSWER=COUNT+TOTAL+SUM(O)

and a warning message will be generated. This is clearly an incorrect


program, as SUM can never be anything but 0.
(b) If more arguments are listed than are correct, the extra
arguments are ignored and a warning message issued. This could happen
if the above example had its calling statement written incorrectly as

LET ANSWER=COUNT+TOTAL+SUM(N,M)

Such a statement will be compiled as though it were written

LET ANSWER=COUNT+TOTAL+SUM(N)

and a warning message will be generated.


If a function does not have its number of arguments defined, no
check is made to determine if the correct number is used. The program
is compiled as written, with responsibility for ensuring tnternal con-
sistency left to the programmer.

It is now possible to illustrate the definition and use of some


routines used as functions,

(1) A routine to evaluate the series


N
1 1
-- .L+ + + +L1
i1 x
1
x
2 x
3 x
N
i-i x
-97-

The routine has two arguments: the number of terms in the series
that are to be summed, and the value to be substituted for x.
In the program preamble:

DEFINE SUM.SERIES AS A REAL FUNCTION WITH 2 ARGUMENTS

Routine definition:

ROUTINE TO SUM.SERIES GIVEN N AND X


DEFINE X AND SUM AS REAL VARIABLES
DEFINE I AND N AS INTEGER VARIABLES
FOR I - I TO N, ADD 1/(X**I) TO SUM
RETURN WITH SUM
END

Routine used as a function:

LET VALUE-SUM.SERIES(1O,2) sets VALUE equal to the st.m

10
.. L+L
+' I +0.999
.2 2 7 3+ 10
i- 2 72 2 2 2

LET VALUE-SUM.SERIES(N.X+Y) sets VALUE equal to the sum

N ; if X-l, -4 and N-3, VALUE- 0.248


i-1 (x+Y)

LET VALUE- SUM.SERIES(40,SIN.F(THETA)) sets VALUE equal to

I 40
i-1 sin(O)i

(2) A routine to compute a square root (see Sec. 1-16-4).


In the program preamble:

DEFINE SQRT AS A REAL FUNCTION WITH 1 ARGUMENT


Routine definition:
ROUTINE FOR SQRT(V)
NORMALLY, MODE IS REAL
LET V-ABS.F(V) ''IF V IS NEGATIVE, TAKE ROOT OF +V
'GUESS' LET S1=V/2
'LOOP' LET S2-(SI+V/SI)/2
IF ABS.F(SI-S2) IS LESS THAN 0.0001,
RETURN WITH S2
OTHERWISE LET S1=S2 GO TO 'LOOP'
END
-98-

Routine used as a function:


same as library function SQRT.F, e.g., LET X=SQRT(Z)
note: SQRT(X) is accurate to 0.0001
SQRT -X)ISQRT(X)
(3) An example to illustrate the definition and use of a routine
with a varying number of arguments. The routine has three arguments
X, Y, and Z; It has the value X if Z=0VX 2 if Z > 0 and X+Y if Z < 0.
In the program preamble:

DEFINE VALUE AS A REAL FUNCTION

Routine definition:

ROUTINE VALUE GIVEN Z, X AND Y


DEFINE X, Y AND Z AS REAL VARIABLES
IF Z EQUALS 0 RETURN(X) ELSE
IF L IS GREATER THAN 0 RETURN WITH X**2 ELSE
RETURN WITH X+Y END

Routine used as a function:


(a) LET VAL-VALUE(2.0), 10 . 0 )t compiles as LET VAL=VALUE(2.0,10.0,0.0)
and sets VAL=100. -- used this way if Z known to be > 0.
(b) LET VAL"VALUE(-1.0,16.0,Z) sets VAL=16 +Z
(c) LET VAL=VALUE(N,Y,X+SQRT.F(N**2)) sets:
VAL= Y if NPO
VAL- Y2 if N>O
VAL- Y+X+SQRT.F(N**2) if N<O
In example (3c) some of the variables present in the routine
argument list when the routine is called have the same names as vari-
ables appearing in the function definition. They are not the same
variables. The variables X and Y used inside the routine are local
variables and are defined only within the routine. The variables in
the calling statement may be global, or they may be local to the call-
ing routine. This is the only way that local variable values can be
passed out of a routine. Let the calling routine be

tSince VALUE has REAL arguments. 2.0 and 10.0 rather than 2 and
10 must be used.
-99-

ROUTINE TO EVALUATE(N,Q,R)
DEFINE XYLNQR AS REAL VARIABLES
LET X-N**2*Q**2 LET Y-X+Q LET ZuX+R
RETURN WITH VALUE(N,YtZ+SQRT.F(N**2))
END

The local variable Y in EVALUATE is assigned a value and used as an


argument in the call on the routine VALUE. The values of N,Y and
Z+SQRT.F(N**2) in the routine EVALUATE are assigned as the initial
values of the local variables Z, X, and Y in the routine VALUE, in
that order. The names in the different routines, although identical,
do not refer to the same memory locations.

2-20 ROUTINES USED AS AMRE GENERAL COMPUTATIONAL PROCEDURES

A routine used as a function returns a single result, but it may


also effect other changes by altering values of global variables.
Generally, a routine can be used as a procedure. A routine used
as a procedure is called on, not to return a single value, but to
perform a task. The task may be to compute one or more values and
return them to a calling program, to modify values of global variables,
or to perform some noncomputational act, such as executing a RESERVE
statement. A routine used as a procedure need not be declared in the
program preamble. There are two ways of examining a routine to deter-
mine whether it can be used as a procedure:
(a) Routines that are used as procedures can have arguments in
an output argument list. These arguments are unsubscripted local
variables that receive values computed within the routine. They are
initialized to zero each time the routine is called. The subsequently
computed values are assigned to named variables in a calling program
when the routine returns control to it.
(b) Routines that are used as procedures return control to a
calling program with a special RETURN statement. Because no single
value is returned as the value of a procedure, there is no need for,
nor any possibility of, executing a statement such as RETURN WITH
arithmetic expression.
A routine can, in general, have both input and output arguments.
Input arguments were discussed in Sec. 2-19; they can be specified
-100-

in routines that are used either as functions or procedures. Output


arguments can only be used in routines that are used as procedures.
They are not always necessary, however, as a procedure can transmit
outputs through global variables. When this is done, the only way
to distinguish a routine used as a procedure from one used as a func-
tion is by the different RETURN statement and by the lack of a defini-
tion in the preamble.
Output arguments are specified by appending the phrase

YIELDING argument list

to a ROUTINE statement. An eu.put argument list contains the names


of local variables, as in the statement

ROUTINE TO ANALYZE.CIRCLE GIVEN RADIUS YIELDING AREA AND CIRCUMFERENCE

In this statement, the local variable RADIUS is used to transmit an


input value from the calling to the called program. The local vari-
ables AREA and CIRCUMFERENCE are used to transmit output values from
the routine to calling programs.
Routines that are used as procedures are called by the statements

CALL routine now


PERFORM routine ncw
NOW routine name

If argument lists are used, they are written after the routine name.
Various forms of argument list structures can be used. The statements
below are equivalent:

CALL TARGET GIVEN RANGE YIELDING ELEVATION AND CHARGE


CALL TARGET (RANGE) YIELDING ELEVATION, CHARGE
NOW TARGET THE RANGE YIELDING ELEVATION AND CHARGE
PERFORM TARGET (RANGE) YIELDING ELEVATION, CHARGE

The following example shows how a routine used as a procedure is


defined and how it can be used:
Routine definition:

ROUTINE FOR CIRCLE GIVEN RADIUS YIELDING AREA AND CIRCUMFERENCE


DEFINE RADIUS, AREA AND CIRCUMFERENCE AS REAL VARIABLES
LET CIRCUMFERENCE- 2*PI.C*RADIUS
LET AREA- PI.C*RADIUS**2
RETURN
END
-101-

Routine used in a program:

(a) READ R CALL CIRCLE GIVEN R YIELDING P AND C


(b) IF A+B < 0 PERFORM CIRCLE(A) YIELDING A,B

In (a) the routine CIRCLE is given the value R as an input argu-


ment. Using this value for the local variable RADIUS, it computes
the values AREA and CIRCUMFERENCE and assigns them to the output argu-
ments P and C, respectively. The variables P and C are not used
within the routine CIRCLE; they receive new values when the routine
returns to the calling program.
In (b) the variable A appears in both the input and the output
argument list. When this is done there is no conflict, as there is
a clear order in which input and output arguments are coummunicated.
First, the initial value of A is transferred to the local variable
RADIUS. Next, the computations of the routine are performed. Finally,
new values of A *nd B are set when the routine returns to the calling
program.

(c) CALL CIRCLE(X+Y**2+Z**2+(P/Q)) YIELDING AREA AND CIRCUM

In (c) an expression is used in the input argument list to trans-


mit a value to RADIUS, the typical use of an input argument. Output
arguments, however, can only be variables (which may be subscripted)
as they do not denote values, but memory locations in which values
are stored.
The "correct" number of arguments for a routine used as a pro-
cedure can be declared in a program preamble by a statement of the
form

DEFINE naw AS A ROUTINE GIVEN i ARGUMENTS YIELDING i VALUES

As usual, some variations are allowed: n may be a list of routine


names and the word ROUTINES used; the word A is optional; WITH and
GIVING are synonym for GIVEN; ARGU*IENTS is a synonym for VALUES; both
the GIVEN and YIELDING phrases are optional. Examples of each of
these variations are given in later sections.
If a greater or smaller number of arguments Appears in a CALL or
a ROUTINE statement than were defined as correct in a program preamble,
-102-

the same rules that apply to functions are observed. Missing argu-
ments in input lists having les than the "standard" number of argu-
ments are assumed to be zero and additional arguments are ignored.
Additional arguments in output lists are ignored, and missing argu-
muets, because they are needed to receive output variables, are created
by the compiler. The values transmitted to them are not accessible
to the calling program. Warning messages are issued.
If a routine Is defined vwth only GIVING arguments, it is assumd
to have no YIELDING values; if it is defined vith only YIELDING values,
it is assumed to have no GIVING argumecns.

2-21 .OITIES USED AS FUNCTIONS AND AS PROC• UR•S

Often there is a possibility of using a routine as both a function


and a procedure. The choice depends upon the number of output values
the routine returns and the manner in which the routine is usee. A
routine can be used as a function and as a procedure by using both
types of RETURN statements. When the routine returns from a RETURN
WITH statement, it returns a value to a calling program; vhen it re-
turns from a RETURN statement, it makes output assignments, if there
are any, and returns to the statement follovi.ig the CALL.
The routine CIRCLE of the previous section can be used as an
example of hoy a routine can be vritten and used as both a function
and a procedure.
In the program preamble:

DEFINE CIRCLE AS A REAL FUNCTIONq

Routine definition:

ROUTINE FOR CIRCLE GIVEN R AND N YIELDING A AND C


DEFINE R, A AND C AS REAL VARIABLES
DEFINE N AS AN INTEGER VARIABLE
LET A-PI.C*e*2 LET C-2*PI.C*R
IF N-O RETURN ELSE RETURN WITH A
END

Routine used:

(a) LET COST-DOLLARS.PER. SUARE.FOOT*CIRCLE(RADIUS, )


(b) READ R CALL CIRCLE(R,O) YIELDING AREA AND CIRC
LET COST-DOLLARS.?ER.SQUjtAE. FOOirAREA
LET 'ENGTH-NUMBER.OF.STRANDS*CIRC
-103-

Notice the added input araumwnt that determines how the routine is
used so that a proper return is affected. A code mway be provided
sithe: this way or as a global variable.

2-22 ARRAY POINTERS AS ROUTINE ARGC7M

Thus far, all routine arguments were either arithmetic expres-


aione or variables. They were expressions in input lists because,
"a was indicated, such lists transmit values from calling to called
programa. They were variables in output lists because values compited
in routines are asigned to them. The transmission of entire arrays
was not mentioned.
Array pointers can be used a arguments of routines. When an
array pointer is used in an argument list, the pointer to the array is
passed to the routine. This pointer is used in place of a local vari-
able pointer that appears in the routine. An array pointer can be
used in an input or output argumemt list. There is no transfer of
values of an array before or after a routine is executed as there is
when unsubscripted variables or expressions are used as arguments;
retrieval and assignment of array values during execution are accoam-
plished through array pointerm.
When an array is used as an argument of a routine, its dimension-
ality must be specified in a DEFINE statinment in the routine. Each
use (call) of a routine that his. array afjrgits mast have arrays of
the same dimension in its argumant lists. The following prorram
illustrates the use of an array name in a routine used as a function:

ROUTINE FOR VECTOR.PRODUCT(XY)


DEFINE X AND Y AS REAL. 1-[1MENSIOftAL ARRAYS
DEFINE SUM AS A REAL VARIABLE DEFINE I AS AN INTEGER VARIABLE
FOR I - I TO DIM.F(X(#)), ADO X(I)*Y(1) TO SLM
RETUF4 WITH SLM
END

In the above routine X and Y are local arrays. When the routine
is called, pointer value arv given to them. If the ro'utine is called
as VECTOR.PRODUCT(COST(*),L#MIT(*)), the statement FOR I - 1 TO
DIM.F(X'*)), ADO X(I)*Y() TO SLIM is intorpreted as FOR I - I TO
DIM.F(COST(*)), ADv COST(I)'UNIT(I) TO SUM.
-104-

If a program has the arrays LIST and VECTOR defined and the
folloving values:

LIST(1) a 2 VECTOR(1) a 4
LISTh2) • 3 VECTOR (2) - 6
LIST(3) - 7 VECTOR(3) - 0
LISTi'4) a - VECTOi,(4) aI1
LIST(5) • 0 VECTOR(5) -5

the statement LET VALUE-VECTOR.PRODUCf(LIST(*),VECTOR(*)) set* VALUE-11.


Arrays used as argumcnts need not be RESERVED in a routine unless
they have not been RESERVED previously. If they are reserved vithin
a routine, they must appear as both input and output arguments so that
the location of the newly allocated memory can be passed back to the
calling program. In this respect, array arguments are unlike sub-
scripted local variables that must be RESERVED at the beginning of
a routine.
The important features to remember about arrays used as arguents
are (1) the pointer to an array is transmitted, rather than the indi-
vidual element values, an. (2) the dimenslonality of the array must
be declared in the routine. Some sample prngrams illustrate these
points.

(1) A routine to compute the trace of a matrix. The trace of


a matrix is defined as the sum of its diagonal elements
N
tr(A) - A(II)
1-1

The array A must have both dimensions equal; it must be defined by a


sttment such as RiSERVE A(*,') AS N BY N. The folloving routine
uses an array name a oce of its arguments and the size ,'f its dimean-
sions as another.
In the program preamble:

DEFINE TRACE AS A REAL FUNCTION WITH 2 AQGUMENTS

Routine definition:
-105-

ROUTINE TRACE(N.MATRIX)
DEFINE SUM AS A REAL VARIABLE
DEFINE MATRIX AS A REAL, 2-DINENSIONAL ARRAY DEFINE I AND N AS
INTEGER VARIABLES
FOR I - 1 TO N, ADO MATRIX(TI) TO SUM
RETURN WITH 3U1 END

Routine used In a program:

(a) To evaluate the trace of a matrix called TABLE


LET VALUE-TRAtE(DIM.F(TABLE(I,*)).TABLE(*.*))
(b) To sum the first 5 diagonal elements of TABLE
LET VALUE-TRACE(5.TABLE(*,*))

Nitice that a routine of the form of SUP.SERIES (see p. 97) can-


not be used for this purpose, as it transmits the value of an argent
to be summd and not a pointer. A function such so TRACE can be used
several tinos in the same expression vith different arguments, as:
LET SUI0-TRACE(IO TABLE(*,*)) + TRACE'Y,ROSTER'*,')) +
TRACE (DIM. F1X(I ,*)).,(',)

(2) A routine using array arguments and defined am a function,


but doing more than merely returnin5 a computed v,-lue to a program
calling it.
In the program preamble:

DUr'NE PROCESS.DATA AS A REAL FUNCTION

Routine definition:

ROUTINE TO PROCESS.DATA GIVEN CODE, LISTI AND LIST2


NORMALLY, MODE- INTEGER
DEFINE LISTi ANC LIST2 AS I-DIMENSIONAL ARRAYS
IF CODE IS GREATER THAN 0 GO TO PRODUCT
OTHERWISE FOR I - I TO DIM. F(LISTI(')),
DO LET LISTI(I)-SQRT.F(LISTI(I))
LET LIST2(I)-SQRT.F LIST2(I))
REPEAT
'PRODUCT' RETURN WITH VECTOR.PRODUCT(LISTI(*).LIST2(*))
END ''OF ROUTINE PROCESS.DATA

Routine used in program:

:f PROCESS.DATA is cailed vith -ODE 0, it returns the value


of VECTOR.PRODJCT (see p. 103) to the cailing roupine; it does
not alter the values c! the srrays in the artg,=wnt list. If
called with CODE - 0, the rouzine replaces the elements of LISTI
and LIST2 (or. more preciselv. the elmnt. indicated bY the
-106-

array pointers used in the calling program) with their square


roots and returns with the VECTOR.PRODUCT of the altered arrays.

(3) A routine adding two two-dimensioral arrays together and


storing their sum in a third array.
In the program preamble:

Nothing needcd since routine is used as a procedure.

Routine definition [note the use of comments in the ROUTINE statement]:

ROUTINE TO ADD.iLiATRICES GIVEN ''INPUTS'' A,B AND "OUTPUT"1 C


DEFINE A, P, AND C AS REAL, 2-DINENSIONAL ARRAYS
NORMALLY, MOD'-INTEGER
FOR I - 1 TO DIM *.F(A(*,*;), FOR J - 1 TO DIM.F(A(1,*)),
LFT C(I,J)-A(I,J)+B(IJ)
REI URN• END

Routine used in program:

(a) PERFORM ADD.MATRICES GIVEN COST.TO.MAKE(*,*),


COST.TO.SHIP(*,*), A1W TOTAL.COST(*,*)
(b) IF DIM.F(A(l,*)) EQUALS IM.F(B(1,*))
NOW ADD.MATRICES (A(*9*),B(*,*),APLUSB(*,*))
OTHERWISE CALL ERROR(1)
(4) A routine illustrating the use of local subscripted vari-
ables in a routine. It uses the routine TRACE (see p. 104) and a
locAl array TEr'o compute a fuaction of an input array without
changing any values of the input a-r~y itself.
In the program preamble:
DEFINE QUANTITY AS AN INTEGER FUNCTION

Routine definition:
ROUTINE QUANTITY GIVEN N AND MATRIX
DEFINE MATRIX AND TEMP AS REAL, 2-DIMENSIONAL ARRAYS
DEcINE N AS AN INTEGER VARIABLE
RESERVE TEMP(*,*) AS N BY N
FOR I - 1 TO N, FOR J 1 TO N,
LET TEMP(I,J)uMATRIX(I,J)**2
RETURN WITH TPACE(NTEMP(*,*)) END
The local variables I, J, and TEMP are "created" when the routine
is :alled, as wheat a callipg program contains the statement

LET QuQUANTITY(NO.SEGS, DISTANCE.TABLE(*,*))


-107-

The variables I and J have the NORMALLY conditions of the program


preamble, as they are not mentioned in the routine preamble. The
array TEMP is defined as REAL and two-dimensional in the routine pre-
amble. Once TEMP has been reserved, it can be used in calls on other
routines; this is done in the call on the routine TRACE.
Notice that QUANTITY has been defined as an INTEGER function.
Because all the variables and the function TRACE are REAL, a conver-
sion is made at the RETURN statement to assign an INTEGER value to
QUANTITY before it returns to the program that called it.
(5) A routine illustrating the use of an array pointer in an
output argument list. It is used as a monitor routine within a pro-
gram to record array reservations for REAL, one-dimensional arrays.
The array pointer appears in the output list ao that the location of
the allocated space caa be returned to the array pointer in the call-
ing program.
In the program preamble:

Nothing needed since the routine is used as a procedure.

Routine definition:

ROUTINE MONITOR GIVEN CODE, N YIELDING NAME


DEFINE CODE AND N AS INTEGER VARIABLES
DEFINE NAME AS A REAL, I-DIMENSIONAL ARRAY
PRINT 1 LINE WITH CODE AND N AS FOLLOWS
RESERVE EXECUTED FOR ARRAY *** LENGTH ***
RESERVE NAME(*) AS N
RETURN
END

Routine used in program:

(a) CALL MONITOR (1,10) YIELDING VECTOR(*)


(b) CALL MONITOR GIVEN 4 AND I*J YIELDING LIST(*)

(6) A program illustrating a routine used as a procedure. Note


the use of global variables and arguments in transmitting data from
the main program to the routines and back again.

__.
-108-

PREAMBLE
NORMALLY, MODE IS INTEGER
DEFINE COSTS AS A 2-DIMENSIONAL ARRAY
DEFINE MODE.FACTORS AND CLASS.FACTORS AS I-DIMENSIONAL ARRAYS
DEFINE CAPACITY AS A 4-DIMENSIONAL ARRAY
DEFINE FROM, TO,MODE AND CLASS AS ''GLOBAL'' VARIABLES
END

MAIN
READ NFROM, NTO, NMODE,NCLASS ''READ MAXIMUM DIMENSIONS
RESERVE COSTS(*,*) AS NFROM BY NTO, MODE.FACTORS(*) AS NMODE,
CLASS.FACTORS(*) AS NCLASS,CAPACITY(*,*,*,*) AS NFROM
BY NTO BY NCLASS BY NMODE
READ COSTS, CLASS.FACTORSMODE.FACTORS ''READ INITIAL DATA
'REQUEST' REAO FROMTOMODE,CLASS
'INQUIRE' CALL RESERVATION YIELDING ANSWER
IF ANSWER EQUALS 1
NOW FIND.COST YIELDING PRICE
PRINT 1 LINE WITH MODE,CLASSFROM,TO,PRICE THUS
MODE * CLASS * RESERVATION FROM ** TO ** IS AVAILABLE FOR *** DOLLARS
GO TO ''NEXT CUSTOMER" REQUEST
OTHERWISE ''FIND OTHER SPACE
SUBTRACT 1 FROM CLASS
IF CLASS IS GREATER THAN 0 GO TO INQUIRE
OTHERWISE LET CLASS=NCLASS
SUBTRACT 1 FROM MODF
IF MODE IS GREATER THAN 0 GO TO INQUIRE
OTHERWISE PRINT 1 LINE WITH FROM AND TO LIKE THIS
THERE IS NO TRANSPORTATION AVAILABLE FROM ** TO ** TODAY
GO TO REQUEST
END ''OF MAIN ROUTINE''

ROUTINE FOR RESERVATION YIELDING ANSWER


IF CAPACITY(FROM,TO,CLASS,MODE) IS GREATER THAN 0
SUBTRACT 1 FROM CAPACITY(FROM TO,CLASS,MODE)
LEI ANSWER=1 RETURN
ELSE LET ANSWER=O RETURN
END

ROUTINE TO FIND.COST YIELDING SUM


LET SUM=COSTS(FROM.TO)*CLASS.FACTORS(CLASS)*MODE.FACTORS(MODE)
RETURN END
The above program processes requests for transportation reserva-
tions. It reads customer requests for reservations on certain modes

of transportation (train, bus, airplane), in seats of a certain type

(first class, economy, tourist), from specified locations to specified


-109-

destinations. A reservation 4S made if there is unused capacity in


the category requested. When a reservation is made, a space is
assigned and the reservation is costed and reported. Costs are based
on distance and type of accommodation. If a space is not available
in the category requested, a search is made through successively lower
classes and modes until eithvr a space is available, or all spaces
have been examined and determined unavailable. This program assumes
ttkere is another routine that returns spaces to the system when they

are vacated.
The points to note in this program are:

(a) The program preamble sets the NORMALLV condition to INTEGER,


thereby declaring all variables throughout the program as integers
unless otherwise specified, and declares that a list of variables are

glbal. All other variables are local.


(b) The first READ statement sets initial values for four vari-
ables local to the main routine. If NFROM and NTO are set to 4 and
3 respectively, the program will accommodate requests for travel from
four locations to three locations.
(c) The RESERVE statement allocates storage to the arrays of the
program according to the specifications of the preceding data. These
arrays represent the basic costs of travel between two cities (COSTS),
the class and mode adjustment factors that modify the basic costs
(CLASS.FACTORS and MODE.FACTORS), and the number of spaces initially
available in each class and mode category between two such cities.
(d) The next READ statement initializes the program to the par-
ticular data values that are used in the run of the program.
(e) The next statements handle specific customer requests. Of
particular interest is the use of the global variables FROM and TO,
and CLASS and MODE, to transmit information from the main program to
the routines RESERVATION and FIND.COST. The local variables ANSWER
and PRICE have been used to show how local. variables are used; there
is no particular reason iur not making them global, or for not making
all variables local and communicating all information through argu-
ment lists.
(f) The local variable ANSWER in the routine RESERVATION has

A
-110-

been given the same name as a local variable in the main routine to
show that this can be done without conflict. A corresponding variable
in the routine FIND.COST has been given a different name to show that
the actual name is of no importance; only its location in the argument
list is important. It also illustrates that the value computed as
SUM in the routine FIND.COST is stored in the local variable PRICE in
the main routine when FIND.COST returns to that program.
(g) FIND.COST can also be defined as a function. This is done
by modifying the routine to:

ROUTINE TO FIND.COST
RETURN WITH COSTS( FROMTO)*CLASS. FACTORS(CLASS)*MODE. FACTORS(MODE)
END
and using the routine name in place of the variable PRICE in the PRINT
statement:

PRINT I LINE WITH TYPECLASSFROM,TO AND FIND.COST AS FOLLOWS


The preamble will then be modified to include the statement:

DEFINE FIND.COST AS AN INTEGER FUNCTION

and the NOW statement in the main routine calling on FIND.COST as a


procedure would be removed.

2-23 RETURNING RESERVED ARRAYS TO FREE STORWGE

When a RESERVE statement is executed it allocates a fixed number


of memory cells to arrays named in the statement. The statement

RESERVE TABLE(*,*) AS 10 BY 50

"assigns 500 memory words to the array TABLE when it is executed.


Every array having memory space allocated to it can have this space
returned to the free storage pool of the SIHSCRIPT II system by ex-
ecuting a statement such as

RELEASE TABLE(*.*)

This statement, which in its general form is

RELEASE azr-pointer Zist


returns all elements of TABLE to free storage and causes the array
TABLE to be undefined until it is once more reserved. A statement
such as LET TABLE(1,1) - 1 cannot be executed after TABLE has been
released, since, for all practical purposes, the array TABLE does not
exist.
This feature is useful in programs that can be structured so
that all of their arrays need not be in storage at the same time.
The RESERVE-RELEASE feature can be used to define one or more arrays
that fit within memory capacity, operate on these arrays, release
them, define new arrays, operate on them, and so forth. The feature
is useful for executing programs that exceed computer capacity.
Because local arrays are not automatically released when a
RETURN statement is executed in routines in which they appear, a
RELEASE statement ahould be executed before returning. Should a
programmer forget to RELEASE a local array before returning from a
routine, the space allocated to the array will be forever inaccessible,
its pointer having been destroyed during the return operation. It is
not possible for SIMSCRIPT II to RELEASE all local arrays automatically.
since some of them may contain pointers to sections of global arrays.
The following routine illustrates the dynamic reservation and
release of a local array within a subprogram:

ROUTINE FOR ANALYSIS GIVEN ARRAY


DEFINE ARRAY AS A REAL, 2-DIMENSIONAL ARRAY
DEFINE TEMP AS A REAL, 2-DIMENSIONAL ARRAY
RESERVE TEMP(*,*) AS DIMF(ARRAY(*,*)) BY DIM.F(ARRAY(I,*))
FOR I-l TO DIM.F(ARRAY(*,*)), FOR J=1 TO DIM-F(ARRAY(1,*)),
LET TEMP(I,J)-ARRAY(I,J)
PERFORM ROW.PERMUTATION GIVEN TEMP(*,*)
LET X= DETERMINANT(TEMP(*,*))
RELEASE TEMP(*,*)
RETURN WITH X
END

ROUTINE ROW.PERMUTATION GIVEN MATRIX


" GENERATES A RANDOM PERMUTATION
" AND EXCHANGES ROWS OF THE INPUT
" ARRAY
END
-112-

ROUTINE FOR DETERMINANT GIVEN MATRIX


" COMPUTES THE DETERMINANT OF
"THE INPUT MATRIX
END

2-24 GLOBAL VARIABLES, ROUTINES, AND SIDE EFFECTS

When global variables are used in routines that interact with


one another, great care must be exercised to prevent unwanted side
effects. An expected change in a program is a change in value of one
or more variables that is obvious, or at least expected, from the
form of a statement. A side effect is a change that is not apparent
from the form of a statement alone. Side effects are important, as
they can cause unexpected and unwanted results if they are not taken
into account. The following routine illustrates a way in which a
side effect can enter into a program:
Routine definition:

ROUTINE VALUE(X)
LET A=SQRT.F(X)
RETURN WITH 4*A+A**3
END

Routine used in a program:


In the preamble:

DEFINE A,B AND C AS REAL VARIABLES


DEFINE VALUE AS A REAL FUNCTION

In the main program:

READ X AND A LET Z-A+(VALUE(X)*C)

Since X is not defined in the program preamble, it is a REAL local


variable. If A=2, C=1, and X=9, Z is evaluated as follows: (1)
application of the parentheses rule evaluates (VALUE(X)*C) first,
setting A-3 and VALUE=39, and (2) application of the operator prece-
dence rule adds the terms A and VALUE together, setting Z=42. The
side effect is the alteration of the value of A within the routine
VALUE.
If the above computation had been programmed differently, the
computed value of Z might not have been the same. Thu above LET
-113-

statement and the ones shown below look alike on the surface but pro-
duce different results in the context of the program.
In the main program:

READ X AND A LET B-A LET Z-B+(VALUE(X)*C)


If we again let A=2, C=1, and X=9, the two LET statements are evaluated
as follows: (1) Bx2; (2) the parentheses rule evaluates (VALUE(X)*C)
setting A-3 and VALUE-39; and (3) the operator precedence rule adds
the terms B and (VALUE(X)*C), setting Z=41. This differs from pre-
vious results.
Side effects are commonly introduced by using functions in FOR
phrase control expressions that are evaluated before each iteration,
and in complex logical expressions that may not always be evaluated
completely (see p. 137). These side effects can be eliminated by
(1) being aware of their existence, and (2) using local variables.
The following program segment shows how a local variable can be used
to inhibit a side effect that the routine FN is assumed to produce:

Write: LET V=FN(K)


FOR 1=1 TO V,LET A(I)=O
Instead
of: FOR I=1 TO FN(K),LET A(I)=O

Use of the local variable V also makes the program more efficient,
as it eliminates the evaluation of FN(K) before each iteration of the
loop.

A 2-25 RECURSIVE ROUTINES

All SIMSCRIPT II routines are recursive, meaning that they can


call upon tthemselves. The concept of recursion is illustrated ia the
following routine, which computes the value of the factorial of n,
where factorial (n)-n*(n-l)*(n-2)*... *(2)*(1).

ROUTINE FOR FACTORIAL(N)


IF N-1, RETURN WITH 1
ELSE RETURN WITH N*FACTORIAL(N-1)
END
The routine calls on itself repeatedly until it has reduced its

LI
-114-

argument to 1. If this function were called with N-4., it would be


evaluated in the following steps:

FACTORIAL(4)-4*FACTORIAL(3)
-4* (3*FACTORIAL(2))
P*3* 2*FACTORIAL(l)))
-4"(3"(2*(1)))
-24

This is not an efficient way to compute a factorial, but it does


illustrate the concept of a recursive call.
While recursively defined routines are not comon, they are ex-
tremely useful in some computing areas -- theorem-proving and language
translation, for example.
Recursive routines are important because their local variables
are unique to each routine call; each call has a separate "memory"
that shares nothing with previous calls except their common routine
structure. Global variables are, of course, defined across all levels
of recursion, as their names represent the same values at all points
in a program. Global variables and values passed in argument lists
are two ways that recursive routines can communicate at different
levels.
Program efficiency and communication are two reasons why one
might want to have nonrecursive routines. The mechanism for isola-
ting variables from a program and making them local, not to a routine
but to each call of a routine, is complicated. Computer time can be
saved if this isolation is eliminated. Isolating local variables of
routines between routine calls also makes it impossible for a routine
to transmit information from one call to another through a local vari-
able. In recursive routines this can only be accoaplished by global
variables or argusents.
All the local variables of a program, or selected local variables
in individual routines, can be defined as SAVED or RECURSIVE. If a
variable is SAVED it is stored in a meory location within a routine
it is local to, and all references to it access this sam location.

tUnless. of course, a global variable name has been locally


defined in somw routines.
-113-

A SAVED variable is not released when control returns to a calling


program. If a variable is RECURSIVE it is stored in a memory location
separate from the routine it is local to -- there is one location fer
each recursive call on the routine and each call accesses a different
location. RECURSIVE variables are released when control returnp to
a calling program. There are three different kinds of local variables:
arguments, SAVED variables, and RECURSIVE variables. Arguments need
not be defined, as this is done when they appear in input and output
argument lists in ROUTINE statements. Arguments are always stored as
RECURSIVE variables.
All local variables in a program, except arguments, can be declared
as SAVED or RECURSIVE by using the phrase

TYPE IS SAVED or TYPE IS RECURSIVE

in the last NORMALLY statement of a program preamble, as in

NORMALLY, MODE IS REAL, TYPE IS SAVED

Since the last NORMALLY statement in the program preamble applies to


all local variables unless they are otherwise qualified, this state-
ment sets a background condition that is binding on all unqualified
variables. If a TYPE phrase is not used, all local variables are
treated as RECURSIVE.
Within routines, local variables can be declared as SAVED or
RECURSIVE in a NORMALLY statement or in DEFINE statements. In DEFINE
statements, use of the words SAVED or RECURSIVE is simil., to use of
the property words that define mode. A routine might contain the
statements:

DEFINE VALUE AS A REAL,RECURSIVE VARIABLE


DEFINE XY AND Z AS RECURSIVEINTEGER VARIABLES
DEFINE QUANTITY AS A SAVED VARIABLE

Local arrays can be treated as SAVED ar RECURSIVE by making their


base pointers SAVED or RECURSIVE. Thus, one nltiht vrite

DEFINE TABLE AS A REALSAVED,2-DIMENSIONAL ARRAY

An important difference between SAVED and RECURSIVE local vari-


ables lies in their initialized value when a routine is called. A
-116-

RECURSIVE local variable has an initial vr]ue of zero each time the
routive in which it appears is called. Recursive variables are often
used for this property alone. A SAVED local variable retains the
value left in 1'.s storage location when the routine was last used.
Thus, routines can use SAVED variables to pass messages from call to
call concerning their operations. The first time a routine is called,
all its local variables, both SAVED and RECURSIVE, are zero.
Recursion can best be understood by shoving an example. The
program below uses Horner's method for evaluation of polynomials.
This method has the computational advantage of requiring only 2(K-1)
arithmetic operations to evaluate a polynomial, fewer than are re-
quired by straightforward evaluation, and it expresses a polynomial
of form A(K)=A(K-I)*X+...+A(1)*X**(K-1) as the recursive form
A(K)+X*(A(K-1)+...+A(1)*X.*(K-2)). The following brief SIMSCRIFT II
routine demonstrates a program for evaluating this form:
In the program preamble:

DEFINE POLYNOMIAL AS A REAL FUNCTION

Routine detinition:

ROUTINE FOR POLYNOMIAL GIVEN A,X AND K


DEFINE A AS A I-DIMENSIONAL,REAL ARRAY x
DEFINE X AS A REAL VARIABLE
DEFINE K AS AN INTEGER VARIABLE
IF K-0, RETURN WITH 0 ELSE
RETURN WITH A(K)+X* POLYNOMIAL(A(*),XK-1)
END

To illustrate how the routine works, we describe the evaluation• ,f


the polynomial 9.2 + 2.1X + 3.3X2o The coefficients 9.2. 2.1, an,!
3.3 are stored in an array CI)EF as COEF(3', COEF(2P, and COEF(i),
respectively. The polyn(mial is to be evaluated vith X..O.5.
The routine is called by usinX it an a function in the starement

LET VALUE-POLYNOMIAL (COEF('),0.5,3)

The polynomial is evaluated as


-117-

POLYNOMIAL(COEF(*),0.5,3)=9.2 + 0.5*POLYNOMIAL(COEF(*) ,0.5,2)


=9.2 + .0 * (2.1 + O.5*POLYNOMIAL(COEF(*),0.5,1))
=9.2 + 0.5*"2.1 + 0.5*(3.3
+ 0.5*POLYNOMIAL(COEF(*),0.5 Oý))
=9.2 + 05*(2.1 + 0.5*(3.3 + 0.5*0.0)3
=9.2 + 0.5*(2.1 + 0.5*3.3)
=9.2 + O.5*3.75
=9.2 + 1.875
=11.075

An example of a recursively called routine for destroying a


binary "tree" is shown below. The tree is constructed of two-element,
one-dimensional, arrays that point to each other. To illustrate the
tree-building process, the following program segment forms the apex
of a binary tree named TREE:

NORMALLY MODE IS INTEGER


DEFINE NOD AND NODE AS 1-DIMENSIONAL ARRAYS
RESERVE NODE(*) AS 2
LET TREE=NODE(*) LET NODE(*)=O
RESERVE NODE(*) AS 2
LET NOD(*)=TREE LET NOD(1)=NODE(*) LET NODE(*)=O
RESERVE NODE(*) AS 2
LET NOD(2)=NODE(*) LET NODE(*)=O

END

NOD is used as a dummy .rray name to v-hich a previous NODE pointer is


assigned to allow nodes to connect to the nodes above them in the
tree. The tree constructed by the program above is exemplified below:

TREE

-NOD
e(1) NODE
E (c)t

NOE1 OD E(2) NODER(1) NODE(2)1

et cettra et cetera et cetera et cetera


-118-

A routine to destroy such a tree is shown below. Given the


pointer to the tree, the routine follows all paths in the tree and
destroys the nodes on them.

ROUTINE DESTROY(NODE)
NORMALLY MODE IS INTEGER
DEFINE NODE AS A 1-DIM ARRAY
IF NODE(*) IS NOT ZERO,
FOR 1=1 TO 2 CALL DESTROY(NODE(I))
RELEASE NODE(*)
REGARDLESS
RETURN END
This ro.uLne, when called by a statement such as NOW DESTROY(TREE),
calls upon itself as each node destroys the nodes below it. Since
each node either points to a successor node or is zero, the routine
can tell whether it has to follow a downward path to destroy successor
aodes, or whether it can destroy the ncde it is working on by releas-
ing it. Perhaps the e~siest way to understand this routine is to
construct a typical tree, such as that shown in Fig. 2-9, and follow
the logic through.

F 2-9 Ab tree

Fig. 2-9 -- A binary tree


-119-

By changing one statement, as shown below, the routine can easily


be expanded to destroy not only binary trees, but those containing
limitless branches as well.

ROUTINE TO OESTROY(NODE)
NORMALLY MODE IS INTEGER
DEFINE NODE AS A 1-DIMENSIONAL ARRAY
IF NODE(*) IS NOT ZERO,
FOR I1-TO DIM.F(NODE(*)), CALL DESTROY(NODE(I))
RELEASE NODE(*)
REGARDLESS
RETURN END
The DIM.F function allows each node to have several branches, rather
than only two. Such a tree might look like Fig. 2-10.

Fig 210 A 0

Fig. 2-10 -- A complex tree


-120-

2-26 DEFINITION OF SYNONYMhUS NAMES AND OPEN ROUTINES

It is not at all unusual to have large programs written by more


than one person. Problems ,re often segmented into parts and the
parts coded separately as subprograms. Later, the subprograms are
combined, either manually or automatically by an executive program.
This approach presents a difficulty because great administrative
care must be exercised to ensure that all programmers use the same
names for global and local variables and that they define things con-
sistentLy. The primary purpose of the two ctatements in this section
is to simplify this task.
The statement

DEFINE X TO MEAN Z

means that whenever the word X appears in a program it is replaced


by the word Z; the compiler automatically substitutes Z for X before
interpretation. It will not extract an embedded X, as in the ntame
XR.AY, and generate the name ZRAY.
The general form of the DEFINE TO MEAN statement is

DEFINE word TO MEAN string of words

where "string of words" represents the information punched after the


word MEAN (separated from it by one blank) that extends to the and of
the statement card. A "string" cannot be composed entirely of blanks
or be a comment.
The rule for DEFINE TO MEAN substitution is simple: whenever the
specified word is seen, the string is substituted for it and the
statement compiled with the substitution. Thus, words can be defined

tA word is a name, number, or special character. It is possible


to redefine variable, label, and coutine names, statement keywords,
special characters such as + and /, and numbers, as
DEFINE + TO MEAN *
DEFINE CONS TO MEAN 7.56
DEFINE < TO MEAN (
DEFINE > TO MEAN )
-121-

as synonyms, they can be replaced by ýomplete statements, and so


forth.
The scope of the DEFINE TO MEAN statement is similar to that of
the NORMALLY statement. When used in a program preamble, it extends
throughout an entire program until overridden; when used in a routine,
it holds (until overridden) for that routine only. The effect of
DEFINE TO MEAN statements can be withdrawn by the statement SUPPRESS
SUBSTITUTION and reinstated by the statement RESUME SUBSTITUTION.
The SUPPRESS SUBSTITUTION and RESUME SUBSTITUTION statements should
be placed alme on cards, since substitution takes place for an entire
card as it is read and before the contents are interpreted. If other
statements appear on the same card as a SUPPRESS SUBSTITUTION state-
ment, substitutions are made for such statements (if called for) before
the SUPPRESS command is recognized. To suppress substitution for a
particular word, the word itself is defined, as in the following
e.gample:

SUPPRESS SUBSTITUTION
DEFINE X TO MEAN X
RESUME SUBSTITUTION

If the SUPPRESS statement is not used, the current substitution will


be made for X before the DEFINE statement is recognized, and X will
never be redefined. For example, if X has previously been mentioned
in the statement

DEFINE X TO MEAN QUANTITY

and the SUPPRESS SUBSTITUTION statement is omitted, the redefinition


will be

DEFINE QUANTITY TO MEAN QUANTITY

which is not the desired definition.


DEFINE TO MEAN statements are not limited co preambles, but can
be used anywhere in a program. They can be used to make short, local
substitutions or extensive changes in vocabulary. The following ex-
amples illustrate some uses of the DEFINE TO MEAN statement:
-122-

(a) Use of the statement to change a word in a routine to the


same word used in other routines in a large program. The word repre-
sents a global variable in this illustration.

RCUTINE SAMPLE(X) YIELDING Y


DEFINE TABLE TO MEAN LIST [This statement inserted in existing program.]
DEFINE X AND Y AS REAL VARIABLES
FOR I - 1 TO DIM.F(TABLE(*,*)),
FOR J FROM 1 TO DIM.F(TABLE(I,*)),
ADD TABLE (1,J) TO Y
IF Y IS LESS THAN X RETURN
OTHERWISE LET Y=-I
RETURN END
(b) Use of the statement to change vocabulary. Assume you do
not like the words LET, ROUTINL-, and END, and you prefer to use the
words SET, PROCEDURE, and FINISH instead. If you precede programs
written with these words by the statements

DEFINE SET TO MEAN LET


DEFINE PROCEDURE TO MEAN ROUTINE
DEFINE FINISH TO MEAN END

the programs will be translated into SIMSCRIPT II vocabulary before


compilatio•i. For example, the program

PROCEDURE TO FIND.MAX(X)
DEFINE X AS A 1-DIMENSIONAL INTEGER ARRAY
SET MAX=X(1) ADD 1 TO SET
FOR I - 2 TO DIM.F(X(*)), SET MAX-MAX.F(MAX,X(I))
RETURN WITH MAY
FINISH
when submitted for compilation preceded by the three DEFINE TO MEAN
statements will be compiled as

ROUTINE TO FIND.MAX(X)
DEFINE X AS A I-DIMENSIONAL INTEGER ARRAY
LET MAX-X(1) ADD 1 TO LET
FOR I - 2 TO DIM.F(X(*)), LET MAX-MAX.F(MAXX(I))
RETURN WITH MAX
END

Notice the use of the word LET as both a variable and a key word.
(c) Use of the statement to define macro-instructions. A macro-
instruction is a compound instruction that N generated from one key
word. The statement
-123-

DEFINE LOCAL TO MEAN DEFINE IJ,K,L AND MAS INTEGER VARIABLES

inserts a definition card for the variables IJ.K.L, and ; wherever


the word IOCAL is used. This is useful when a number of routines use
the same local variables. A routine can be written ms

ROUTINE EXAMPLE(X)
LOCAL
DEFINE X AS A REAL VARIABLE

END

nnd, if it is preceded by the above DEFINE TO MEAN etatement, it will


be compiled as

ROUTINE EXAMPLE(X)
DEFINE I,J,K,L AND M AS INTEGER VARIABLES
DEFINE X AS A REAL VARIABLE

END

Entire sequences of statements can be generated directly into a


program by an extended form of the DEFINE TO MEAN statement. This
statement allows more than one line of statements to be substituted
for a particular key word, and it offers greater possibilities for
macro-instruction generation. The statement can be written in two ways:

SUBSTITUTE THIS LINE FOR word and


SUBSTITUTE THESE i LINES FOR word

In the first statement, the contents of the line following the state-
ment is substituted for the key word wherever it appears; in the
second statement, the contents of the following I lines are substi-
tuted. As with the DEFINE TO MEAN statement, totally blank cards and
comments cannot be substituted.
DEFINE TO MEAN and SUBSTITUTE statements can be used freely in
a program with few restri-tions. They can "call on" one another at
different levels of substitution. The following statements show how
a series of DEFINE TO MEAN and SUBSTITUTE statements can be applied
to a program statement and used to translate the words of the state-
ment into legal SIMSCRIPT II code:
-124-

SUBSTITUTE THESE 2 LINES FOR ZZ


SET VALUE-B
GO TO START
DEFINE SET TO MEAN LET
DEFINE B TO MEAN X(I)*Y(I)+1
Program statement:

IF VALUE IS GREATER THAN 0 ZZ ELSE


Translated as:

ZZ is translated to SET VALUE=B


GO TO START
SET VALUE-B is translated to LET VALUE=B and then to
LET VALUE=X(I)*Y(I)+I
Compiled as:

IF VALUE IS GREATER THAN 0


LET VALUE-X(I)*Y(I)+1
GO TO START
ELSE
Certain words, such as statement key words, should be redefined
with extreme caution. If, for example, the word A is defined, as in
the statement
DEFINE A TO MEAN X
and a DEFINE statement such as DEFINE LIST AS A REAL ARRAY processed,
X will be substituted for A, and will create the incorrect statement
DEFINE LIST AS X REAL ARRAY.

2-27 SAMPLE SIMSCRIPT II, LFVEL 2 PROGRAMS

2-27-1 A Data AnaZ',ie ProTr0Y7

This program reacs N data items xl,x 2 ,....,xn into a list. It


then goes through the list computing the average of successive over-
lapping sequences of observations x 1 ,xi+ 1 ,..., xi+ for ?4-1,2,3,...,N-1.
These moving averages are compared with an input tolerance value, and
if they are less than this value, the values of i.i+M, and the average
are printed.
The following problem illustrates the use if the RESERVE statement,
-125-

the READ statement with a subscripted variable, and the use of FOR
loops to control the indexing of subscripted variables: A
PREAMBLE DEFINE LIST AS A 1-DIMENSIONAL ARRAY
DEFINE I,J,M AND N AS INTEGER VARIABLES
END
MAIN READ N
RESERVE LIST(*) AS N READ LIST
READ TOLERANCE. VALUE
FOR M-1 TO N-i
FOR 1-1 TO N-M
DO
LET SUM-O
FOR J-O TO M, ADD LIST(I+J) TO SUM
LET AVERAGE=SUM/(M+l)
IF AVERAGE IS LESS THAN TOLERANCE.VALUE
PRINT I LINE WITH I, I+M AND AVERAGE AS FOLLOWS
ITEMS *** THROUGH *** HAVE AN AVERAGE OF *****
REGARDLESS
LOOP
STOP END

2-27-2 A Data Analysis Progrcw,

This program repeats the computations of the previous problem,


but instead of computing the average of the items xi,... xi+M it coL-
putes the average of a function of the items f(xi),...f(xi+M). As
the function can vary for different problems, the program for com-
puting it& value is called as a routine and is not incorporated directly
into the data analyaij program.
The program below illustrates how to write and use a routine
subprogram as a function.

PREAMBLE DEFINE LIST AS A I-DIMENSIONAL ARRAY


DEFINE I,J,il AND N AS INTEGER VARIABLES
DEFINE VALUE AS A REAL FUNCT:ON
END
MAIN READ N
RESERVE LIST(*) AS N READ LIST
REAL TOLERANCE.VALUE
FOR M-1 TO N-i,
FOR I-1 TO N-M,
LET SUM-O
FOR J,, TO M, ADD VALUE(LIST(I+J)) TO SUM
LET AVERAGE,,SUM/(M+1i)
IF AVERAGE IS LESS THAN TCLERANCE.VALUE
PRINT I LINE W!TH I,YTM AND AVERAGE LIKE THIS
ITEMS *** THROUGH **" 4AVE AN AVERAGE OF *****
REGARDLESS
LOOP
STOP END
ROUTINE FOR VALUE GIVEN VARIABLE
IF VARIABLE IS LESS THAN -1000 RETURN WITH -1
OTHERJISE IF VARIABLE IS GREATER THAN 1000 RETURN WITH 1
OTHERWISE RETURN WITH VARIABLE/100
END

2-27-3 A Matrix MiLtiplication Program

Two matrices (double-subscripted variables) are punched on data


car4s. Matrix A appears in the order A(l,l), A(l,2),...,A(l,H),
A(2,1),...,A(2,M),A(3,1),...,A(N,M). Matrix B appears in the order
B(ll),I(2,l),... ,B(S,1),B(1,2),... B(S,2) ,B(13),...,B(RS). A is
punched row by row, anad B, column by column. The values of the matrix
dimeinsion N,M,R, and S precede the element data.
This program reads the data and, if possible, multiplies the
matrices A and B together to iorn matrix C.
For matrix multiplication tc be effected, M must equal R. The
rule* for computation are

if A has dimensions N, H end


5 has dimeasions X, S then
C has dimensions N, S and the el0eents of C are computed 4s

M
c(I.X) - (1.J),3(J.K)

The program below illustrates the use of the RESERVE statement


with variable dimensions executed in the body of a program. to form
of READ setatmert formats for inputtirg sub•c.ipted variables, nested
FOR loops. and the use of the LIST stateemat.
-127

MAIN
DEFINE I,J,K,MN,R AND S AS INTEGER VARIABLES
READ N, M, R AND S IF M IS NOT EQUAL TO R, PRINT I LINE THUS
MATRIX DIMENSIONS ARE NOT EQUAL, MULTIPLICAI TO.N IMPOSSIBLE
STOP ELSE RESERVE A(*,*) AS N BY M,B(',) AS R BY SC(*.*) AS N BY S
READ A FOR J-1 TO S, rOR 1.1 TO R, READ B(I,J)
FOR II TO N. FOR K-1 TO S, FOR J-l TO M
ADD A(IoJ)*B(J,K) TO C(IK)
LIST A, B AND C
STOP END

2-27-4 A Matznx .MuLtiplication Houtine

This program presents the previous program written as a routine.


It returns a coded message if multiplication is not possible. Unlike
the foregoing program, this one does not assume that the matrix C con-
tains all zeros, and an initialization statement is incorporated into
the routine.
The problem below illustrtes how a routine it vritten and used
as a procedure. it demonstrates the une of input and output argu-
aents in such routines.

ROUTINE TO MATRIX.'JLTIPLY GIVEN A,B AND C, NM,R AND S


YIELDING CODE
DEFINE A, B AND C AS 2-DIMENSIONAL REAL ARRAYS
OEF:NE NMR,S,I,J,K AND CODE AS INTEGER VARIABLES
IF M IS NOT EQUAL TO R LET CODE-O RETJRN
OTHERWISE LET CODE21
FOR I-i TO N, FOR K-1 TO S
DO LET C(IK)-O
FOR C-I TO M, ADD A(IJ)*B(J,K) TO C(i,K)
REPEAT
RETURN END

This routine m'ghit be used in s progra- by¢ callip, on it as

NOW MATRIX.MULTTLY(TABI _I(-*),TABLE2('.1),TABLE3(',"), 41, N2, 43, N4)


YIELDING FLAG
Ir FLAG E?;S 0, GO TO ACTION.1
OTHERWISE LiST TABLF3
-128-

2-27-5 Definition and Use of a Routine as a Function

Here, the program defines a routine to coapute the quantity M


defined as
2 .i2rx3x• 32
M 2- dL 3(1-2x)(3.080 sin -0.7100 sin-2x-+ 0.349 sin -"
8b4 M3LL

For values d-62.4, L-10, and x- 4 the routine is used to compute and
print the quantities
Qi - H- (M-I)2
12

0 if M<m
Q2 - 1 if M , m
2 if M> m
2 2 2 2
Q3 iT (1-q) 2 A3 (l-a)(3.080
2an .- 0.7100 sin 2a
A6(1~)3A 0 -A -0*An

3n2
---- )
+ 0.349 sin
A

MAIN
LET VALUE=M(62.4,10.O,4.0)
PRINT 1 LINE WITH SQRT.F(VALUE**2 - (VALUE-I)**2) LIKE THIS
THE VALUE OF Q1 IS *
LET Q2-O READ SMALL.EM
IF VALUE EQUALS SMALL.EM, LET Q2=1 ELSE
IF VALUE IS GREATER THAN SMALL.EM, LET Q2=2 REGARDLESS
PRINT 1 LINE WITH Q2 AS FOLLOWS
THE VALUE OF Q2 IS *
READ QA AND LITTLE.EH
PRINT 1 LINE WITH M((1-Q)**2,A, LITTLE.EH**2) THUS
THE VALUE OF Q3 IS *
STOP END

ROUTINE FOR M GIVEN D,I. AND X


LET TEMP=(PI.C * X)/L
RETURN WITH (PI.C**2/864)*(D*L**3)*(l-(2*X)/(3*L))*'3.08*
SIN.F(TEMP) - 0.71*SIN.F(2*TEMP) + 0.349*SIN.F(3*TEMP))
END
The routine and main program illustrate the use of a systL.2-
defined conbtant (PI.C), system-defined functions (SIN.F, SQRT.F),
and the transmission of argument values to routines, and shows some
methods by which temporary variables can be used to make computations
-129-

more efficient. Notice that, as there is no preamble, all variables


are implicitly REAL, and all are local to their respective routines -

the variables VALUE, SMALL.EM, Q1, 02, Q,A and LIVTLE.EH are local to
the main routine, and the variable TEMP is local to the routine M.

2-28 MORE ON PROGRAM FORMATS

As described in Sec. 1-09, all 80 card columns can be used for


program statements. As blanKs are ignored between words, a programmer
can design his own program formats by standardizing the number of
blank columns put before and after statements.
Since the SIMSCRIPT 1I compiler reads all 80 columns, a control
statement limiting the number of columns containing valid program
statements is -ed- if program cards are to be sequence numbered or
otherwise identified. If a program cannot be restricted to the first
70 cclumns, say, of a card, error messages will be produced each time
a sequence number is :ead. Of course, comment cards can be use,! to
delimit sequence numbers, as in the following example, but this is
inefficient in large programs.

ROUTINE FOR ANALYSIS GIVEN X YIELDING Y "ANAL 0001


DEFINE X AND Y AS REAL VARIABLES ''ANAL 0002

END

The preamble statement

LAST COLUMN IS integer constant


specifies that columns to the right of the indicated column do not
contain program statements. These columns appear on all program
listings produced during compilation, but do not enter into the com-
pilation process. The symbol "-" is a synonym for the word "IS".
Each time a LAST COLUMN card is used in a preamble, the number of
program statement columns may change. The last LAST COLUMN statement
used in a preamble applies to all subprograms that follow.
The simplest preamble used to specify sequence number columns is:
-130-

PREAMBLE
LAWT LULUMN IS 72
END
This specifies that in all succeeding cards only columns 1 through 72
contain program statements. Columns 73 through 80 are listed but
ignored during compilation.
-131-

iI

Chapter 3

SIMSCRIPT II: LEVEL 3

3-00 A STATEMENT FOR SP.LIFTING NESTED IF STATEENTS

A unique feature of one particular nested IF statement structure


is that a transfer is made out of the nest upon the failure of any
nested test. This is illustrated below.

IF VALUE(ITEM) EQUALS HI,LET PRIORITY(ITEM)-l


IF TIME.DUE(ITEM) < NOW+7,ADD 1 TO PRIORITY(ITEM)
IF WORK.TO.DO(ITEM) > LIMIT. ADD I TO PRIORITY(ITEM)
ELSE
ELSE
ELSE

The failure of any test causes a transfer to a matched ELSE state-


ment that branches o..t of the nest. The essence of the logic of the
nest lies in the word THEN. If a condition is true, computation con-
tinues with the next statement, THEN IF ... , but if any condition is
false, control passes to its matching ELSE and out of the nest. The
THEN IF statement improves the readability of nested IF statements by
eliminating consecutive ELSE statements. In programs containing
sequences of IF statements, if one or more IF is preceded by the word
THEN, some ELSE statements can be eliminated, for when a logical test
associated with a THEN IF phrase fails, control passes to the ELSE
associated with the previous IF. To illustrate, the above program is
rewritten using THEN IF statements.

IF VALUE(ITEM) EQUALS HI, LET PRIORITY(ITEM)-I


THEN IF TIME.DUE(ITEM) < NOW.1, ADD 1 TO PRIORITY(ITEM)
THEN IF WORK.DUE(ITEM) , LIMIT, ADD 1 TO PRIORITY(ITEM)
ELSE

I- ~ .
-132-

The THEN IF statement is only applicable to nested logical tests


in which the falsa condition for each test is the same and where fail-
ure of any test automatically transfers out of the nest. The logic
of a sequence of nested THEN IF statements is shown in the following
flow diagram:

STrue IF False

STrue THNI
False

,3-01 A 6?ATKM'WT ~PO SIMLIG'r:ING *YESTE?2 0XLOOgPS


FOR phrases, with their attached DO and REPEAT loops, can also
be nested. Often two or more FOR phrases end on the sme program
statement, and a Statemesnts are needed to

close all the "open" DO'e, as, for example, in


-133-

FOR 1-1 TO N, FOR K-1 TO N,


DO
LET C(I,K)-O LET D(IK)-O
FOR J-1 TO N,
DO
ADD A(I fJ*B(JoK) TO C(IK)
ADD A I,J )**2*B(JK)**2 TO D(I,K)
LOOP
LOOP
Consecutive LOOP or REPEAT statements can be eliminated by using
the statement ALSO FOR whenever consecutive FOR loops terminate on
the same statement. When an ALSO FOR is used, SIMSCRIPT II automatic-
ally pairs the DO that follows, w4 - the LOOP that matches the DO of
the preceding FOR etatement. Uring this statement, the above example
can be written as

FOR 1-1 TO N, FOR KI1 TO N,


DO LET C(I,K), D(IK)sO
ALSO FOR J=1 TO N,
DO ADD A(IJ)*B(JK) TO C(I,K)
TO D(I,K)
LOOP ADD A(IJ)**2*B(J,K)**2

The following sequence of FOR and ALSO FOR loops illustrates how DOs
and LOOPs are matched when these phrases are interspersed:

FOR
00

FOR
00
ALSO MRo
00

ALSO MRe
00
LOOP
AL SO FOe
00
ALso F"
00
LOOP
-1.34-

3-02 SPE' ZU COMPLEX LOGICAL EXPRESSIONS

Sections 1-04 and 2-12 discussed two types of logical expression.:


expressions that use relational operators to compare two arithmetic
expressions, and expressions that use the operators IS and IS NOT to
compare a single arithmetic expression ar a special name with a speci-
fied property. Logical expressions formed according to either of
these rules are simple logical expressions in thrit they express a
single logical relationship.
Section 1-04 also showed that a logical expression can be enclosed
in parentheses without changing its meaning. Parentheses bind an
expression as a unit and have nc 'ffect on its evaluation. All logical
expressions can be enclosed within parentheses without anw change in
meaning.

VALUE < LIMIT is equivalent to (VALUE < LIMIT) and


SUM IS POSITIVE is equivalent to (SUM IS POSITIVE)

A logical expression can be negated by following it with the


phrase IS FALSE, as in the logical expression

VALUE < LIMIT IS FALSE

The IS FALSE phtase serves a wider purpose than the mere improvement
of readability - it can be used to state a desired condition without
forcing an unnatural transposition nf logiz. For example, a test can
be written as

IF QUANTITY > INVENTORY GO TO ORDER ELSE or as


IF QUANTITY < INVENTORY IS FALSE GO TO ORDER ELSE

with equal effect. For symmetry, the phrase IS TRUE is permitted.


The form selected depends on how a programmer wants a logicrl expres-
sion to appear to a reader.
Simple loRical expression,, containing arithmetic expressions and
relational operators can be assa"bled together to form compound logiocZ
exzproeesiont. Usint e to represent an arithmetic expression and R to
represent a relational operator, a compound logical expression can be
written as

4h.,*
-135-

Form Example

eRe I<X
e Re Re R <X<N
e ReReR e 1
< X <N aSUM
e R e R e R e R eI1 < X < N - SUM IS GREATER THAN 5

In each of these cases all of the expressed logical relationships must


be true in order that the compound expression be true. For example,
in the second illustration, X must be greater than 1 and less than N.
The notation used is actually a shorthand method of writing ) < X and
X < N.
Simple logical expressions can also be combined to form ccmpound
logical expressions by explicitly using the logical operators AND t or
OR. If el and e2 are logical expressions, then
eI AND e 2 is true if both el and e2 are true
e1 OR e2 is true if either el or e2 or both el and e 2 are true

Compound logical expressions can contain more than two simple logical
expressions, as in the logical expression

e1 AND e2 OR e 3 AND e4

When more than two simple logical expressions appear in an unparen-


thestzed compound logical expression with the operators AND and OR,
the operator AND is evaluated fir~t. Parentheses can be used, how-
ever, to indicate a specific order of evaluation. In the absence of
parentheses, the above expression is evaluated by convention as though
it had been written

(a) (e 1 AND e 2 ) OR (e 3 AND e4)

If a program requires some other logic, the statoment can be written as

(b) e, AND (e2 OR e3) AND e4

which means something quite different. Version (a) is true either if


both e1 and e2 are true or if both e3 and e4 are true. Version (b)
is true if eI is true and e 4 is true, and either e 2 or e3 is true.

tIn this context, a coma cannot be substituted for the word


AND.
-136-

Compound logical expressions can be used with IS FALSE and IS


TRUE phrases. An IS FALSE or IS TRUE phrase &lways applies to the
logical expression preceding it. If this logical expression is com-
pound, it must be enclosed in parentheses, e.g., the logical expression

SIS FALSE AND (e 2 OR e 3 ) IS TRUE


A few simple rules that govern the writing and evaluation of
logical expressions ar, given below:

(a) A logical expression enclosed in parentheses remains a


logical expression.
(b) In the absence of parenthesec, AND is evaluated before OR,
that is, f.:om left to right across an expression, successive
logical expressions are used as operands of AND operators,
and these evaluated expressions are then used as operands
of OR operators. Parentheses can always be used to indicate
specific operator hierarchies.
(c) IS TRUE and IS FALSE phrases apply to logical expressions
preceding them. If such a logical expression is compound,
it must be enclosed in parentheses; otherwise the phrase
only applies to the expression adjacent to it.

Some examples that illustrate the writing and evaluation of -om-


plex logical expressions are given below. In these examples, the
variables IJ,K.LM, and N are positive numbers, the variables Q,RS,
and T are negative numbers, and the variable Z is zero.
(a) I EQUALS J is true or false depending on the values I,J
(b2 I EQUALS Q is always false
.) M+N IS POSITIVE is always true
(d) 14+T IS POSITIVE is true or false depending on the values M,T
(e) I > 0 AND J - 0 is always true
(f) I 0 OR R > 0 is always true
(g) I " J AND Z - 0 's true if I equals J, is false other-wise
(h) I J OR Z -0 is always true
(i) I J AND K > N AND R - S is true if all three conditions are
true and false othervise; it is
evaluated a& ((I - J)AND(K > N) AND
(R - S))
(j) " N OR R S is true if any one of the three con-
dittons 16 true; it is false only
-137-

(k) I J AND K > N OR R is true if either of the two


S conditions
around the OR is true; it is evaluated
as (I J AND K - N) OR (R a S)
(1) Z IS ZERO AND (I < 0 OR S < 0) AND Q - T is true only if Q" T
(a) Z IS ZERO AND (I > O OR S < O) ANDQ * T is trie ifQ T
(n) J < K AND (I Q OR S < 0) AND J + K < I is true if J < K and
J+K < I

When a statement containing a compound logical expression is ex-


ecuted, it does not always follow that all logical conditions in the
statement are examined. For example, in the statement

IF X > Y**2 AND COUNT > N, ADD ... ELSE

both logical expressions have to be true for the ADD statement to be


executed. If the first logical expression (X > Y**2) is false, there
is no need to evaluate the second (COUNT > N), as the compound logical
expression X > Y**2 AND COUNT > N can never be true regardless of the
values of COUNT and N. In normal circumstances, the fact that all
parts of a compound logical expression may not be evaluated each time
will cause no undue difficulty. It can cause problems if a programer
uses a function in a logical expression and expects an evaluation
each time. As this evaluation may not always be performed, it is a good
rule not to use functions in the above manner if they have side effects.

.- 03 LOGICAL COT'2ROL PHRASES

A logieaZ contzoZ phrase' contains a logical expression and a


Zogical coztmr' operztor, and is ordinarily used in connection with
a FOR statesent. The logical control phrasee are

WiTH logi-a: ezVr88sic,.


UNLESS Zogia: eTr%-ss;",
WILE Zoi&'ai' e•x'iseV. and
UNTIL loq;a =Ksz
, o

A WITH phrase Modifies the niquence of values that pass from a


FOR phrase to the statements that it controls. Its logical expression
is tested each time a now value of tha FOR phrase control variable is
generated, and if the expression is false the control variable value
is skipptd. This effeCtively passes control arousid these statt"enta
-138-

for a selected set of control variable values. The phrase i.s useful
for screening values before they pass itto FOR-phrase-controlled state-
ments. An example of the use of a WITH phrase in

FOR I - 1 TO N, WITH X(I) LESS THAN CUT.OFF


00 LET BID(I) - PRICE + PROPORTION(PRICE)
ADO 1 TO NUMBER.OF.BIDS
LOOP

In this example the WITH phrase screens out those values of I hetween
I and N for which the logical expression X(I) < CUT.OFF is false. The
program perform as if it had been written as

FOR I - I TO M, DO
IF X(T) > CUT.OFF GO TO LOOP
ELSE L"Et BID(i) - PRICE + PROPORTION (PRICE)
ADD 1 TO NUMBER.OF.BIDS
'LOOP' LOOP

The word WHEN can be used as a synonym for WITH. The word UNLESS
and the phrase EXCEPT WHEN can be used to show that the items papuing
the indicated tast are screened from the loop, rather than accepted.
as iu the program

FOR I - 1 TO N, EXCEPT WHEN X(I' c CUT.OFF


DO LET BID(I) - PRICE + PROPORTION (PRICE)
ADO 1 TO NULBER.OF.BIDS
LOOP

A WHILE phrase allows a FOR Lo direct the sequence of program


control sa long as a cerLain logical expression iu true. Itd logical
expression is reevaluated each time the FOR phrase changes the valus
of Its control variable. Thus. the program

rOR I - 1 TO N, WHILE X(I) LESS THAN CUT.OFF


DO LET 81D(1) - PRICE + PROPORTION (PRICE)
ADO I TO NULER.OF.BILIS
LOOP

terminates the loop as soon as a value of X(1) is greater than or


equal to CUT.OFF. The program perform@ as i it had bean written as
IFOR I.• I TO N
DO IF 41I) - CUTOFF GO TO NEXT
ELSE r"T BID(1) - PRICE * PRORTION (PRICE)
ADO I TO IPgQER.yr3.BID
LOOP
'NE.T'
-1 •9-

An UNTIL phrase allws a FOR to direct the sequence of p'ogrAm


control " long as a certain logical expression is not true. It has
the @sme effect as a WHILE phrase that has an IS FALSE phrase put
after its logical control expression. The program

FOR I - I TO N, UNTIL X(l) > CUT.OFF


DO LET BID(I) - PRICE-+ PROPORTION (PRICE)
ADO I TO NUMBER.OF.BIDS
LOOP

perforum exactly 1_ke the previous program.


WITH, UNLESS, WHILE, and LNTIL phrases can be a:tached to nested
FOR statements. When this is done, each WITH or UNLESS phrase appliaq
to the FOR statement imiedistely preceding it, and each WHILE or UNTI1
phrase applies to alZ pzecoadi1g FOR phrases. The following program
illustrates this:

FOR DELTA- I TO 100 BY 0.5,


FOR Q - DT(1) TO DT(2) BY DELTA.
WHILE(FN(Q) - FN(DT(l)))/(Q - DT(1)) > 0,
FOR V - -Q TO Q BY STEP, WITH GN(V) > MIN
DO
ADD GN(V) TO SUM
ADO 1 TO NUMBER.OF.SEGMENTS
LOOP
'NEXT'

The outer FOR phrases step the variables DELTA and Q through a sequence
of values as long as the logical expression in the WHILE phrase ts
true. A false condition ends the FOR phraso control by transferzing
to 'NEXT'. Each time the variables ,ro stepped and the logi,-al expres-
sion is troe. the .nne. FOR steps the variable V through a sequence
of values. Only those values In the sequence, however, for which the
logical expression in the WITH phrase is true are passed on to the
statements in the DO loop.
Stotences of WITH. UNLESS, WHILE, ad UNTIL phrases car be attechod
to FOR phrases in any combination. %lore than on* of each trpe c-fphrase
is permitted.
UNTIL and WHILE stacewmnts can also be useý! independently. -henn
used this way, the variables appearint within their Inlical express!ms
de not cose from a FOR phrase iteration, but from compmtations perfcr-ue
-140.

within their range. The range of an independent logical control


phrase, like the range of a FOR phrase, is delimited by DO and LOOP
or REPEAT statements. The following example illustrates the use of
an independent WHILE statement in a program:

WHILE NUMBER.OF.SEATS I¶ NOT ZERO,


DO READ PASSENGER
PERFORM TICKETING(PASSENGER)
ADD FARE TO SUM
LOOP

In this example, the value of the global variable NUMBER.OF.SEATS is


assumed to be changed in the routine TICKETING. As long as NUMBER.OF.
SEATS is positive, control is passed to the READ statement after the
LOOP statement has transferred back to the WHILE in expectation of
another iteration. When NUMBEP.OF.SEATS becomes zero, the WHILE state-
merit transfers to the statement following LOOP.
WHILE dnd UNTIL statements can be modified by WITH and UNLESS
phrases, and may be nested with other independent WHILE and UNTIL
statements and with FOR phrasges. When nested WHILE and UNTIL state-
ments end on the same LOOP statement, tie phrases ALSO WHILE and ALSO
UNTIL can be used to eliminate the redundant LOOP.
Since there is no automatic termination of an independent WHILE
or UNTIL phrase as there is with a FOR phrase, a programmer must be
careful not to program a nonterminating loop, as in the following
program segment:

WHILE I IS GREATER THAN J,


DO READ X
ADD X TO SUM
LOOP

This loop is not teriiinal, as the values of I and J are not affected
by the loop.

3-04 RETURNING ROUTINES TO FREE STORAGE

The RELEASE statement can also be used to return space occupied


by routines to free storage. Used in conjunction with the release of
arrays, this provides a powerful facility for fitting large programs
into core. A routine is released by using its name in a RELEASE state-
ment, as in
-141-

RELEASE START, INTERRUPT, AND ALLOCATE


RoutineI and array names can be used in the same RELEASE statement.
The general form of the RELEASE statement is

RELEASE array pointer and routine name list

Each routine must be declared as RELEASABLE ttt- 'i eligible for


use in a RELEASE statement. This is done in the preaml-te, and must
be done individually for routines by prefacing the word ROUTINE or
ROUTINES in a DEFINE statement with the word RELEASABLE, as in the
statements

DEFINE START AND MONITOR AS RELEASABLE ROUTINES


DEFINE INITIALIZE AS A RELEASABLE ROUTINE and
DEFINE RTN AS A RELEASABLE ROUTINE WITH 3 ARGUMENTS, YIELDING 1 VALUE

As an exa ple of the use of the RELEASE statement, consider the


program below. The routine START is called to initialize global vari-
ables; after this is done it returns to the main program and is never
called again. As the program is very large, the scheme described is
employed in order to use the space taken by the routine START for
an array called MATRIX.

PREAMBLE
DEFINE START AS A RELEASABLE ROUTINE
program NORMALLY, MODE IS REAL
preamble et cetera
END

MAIN
main PERFORM START RELEASE START
routine RESERVE MATRIX(*,*) AS N BY N
other computations
END
ROUTINE START
computations
other RETURN END
routines *

other routines of the program

tExcept for in-line functions (see Table 2-4).


ttThis may not be necessary in some SIMSCRIPT II implementations.
-142-

3-05 EXTERNAL STORAGE AND RETRIEVAL OF ROUTINES

Programs that exceed computer capacity can be run if there is a


facility for storing parts of programs on external storage devices
such as drums, disks, and magnetic tapes, and reading them back into
core storage when they are needed. For various reasons, it is impos-
sible to design statements that provide such facilities independent
of computer operating systems, i.e., as part of a machine-independent
programing language. The task of this section is not to specify
statements for the storage and retrieval of routines, but to describe
ways in which this can be done; to discuss the effect of different
schemes on SINSCRIPT II programs; to suggest what seem to be useful
statement forms; and to provide guidelines for particular implementa-
tions of storage and retrieval statements on a variety of computers.
Two general methods are available for executing large programs:
program overlay and dynamic program relocation.

3-05-1 Plsogr Overlay

The easier of the two program storage and retrieval schoeme pre-
sented involves the partitioning of a program into overlay sections,
with each section containing one or more routines. If the partitioning
is done well (and if a program permits it to be done well), a program
can be executed by sequentially bringing overlay sections into core
on top of one another. If routines within particular sections only
call on routines in the same section or on routines permanently located
in coze, this method is efficient. On the other hand, if routines call
upon routines in other sections, time is spent replacing these sections
in core so that the routines may be loaded and executed. Overlay is
an efficient technique for sequentially designed programs; its effi-
ciency decreases as the inLeraction between overlay sections ;ncreases.
There are several ways in which overlay can be implemented. All
involve keeping a copy of each overlay section on an external medium
and loading it into a fixed overlay area when the section is needed.
Since the same copy is loadod each time a section is overlayed, it is
impossible to transmit values of SAVED local variables between overlays.
-143-

When a section is overlayed, all the SAVED local variables In the


section's routines are reset to zero. Care must be exercised in
using SAVED local variables with an overlay feature.
The overlay of an overlay section can be invoked by a special
statement such as

LOAD overla section now

or it can be invoked automatically, by the use of a routine name within


an overlay section somewhere in a program. Operiting systems having
an automatic overlay feature keep track of the location of all routines
at all times, and bring overlay sections into core if routines within
them but not in core are called. Routines are generAlly located within
named overlay sections by control cards placed in a program card deck.
In some implementations, howevei, program preamble statements may have
to explicitly make such correspondences, such as the statement form

OVERLAY SECTION naoe CONTAINS ROUTINES routine name list

3-05-2 Dynamic Progrw, Relocation

A more general program storage and retrieval scheme allows indi-


vidual routines to be removed from core and restored at a later time,
perhaps in a different place. While providing a greater amount of
flexibility than does program overlay, such a scheme involves more
effort to make it efficacious. Some computers, because of their
internal design, may not even be able to implement the feature. As
with overlay, two implementation methods are available: automatic
relocation control, and explicit dynamic program control.
As pointed out above, with automatic overlay the mention of a
roitine in a program causes it to be loaded into core if it is not
already there. Automatic relocation control differs from this pro-
cedure in that a relocatable routine reed not always be placed in
the some core locations.
Under explicit dynamic program relocation, a program is removed
from core and saved an s-,m axzorr~l medlujm by a statement of the
form
SAVE •, .' ',..
-144-

Execution of this statement both copies a routine and releases its


memory apace. Loading of the routine at a later time can be dune in
either of two ways: automatically, when the routine is called, or
through a special statement. If loading is done automatically, several
things are needed: the routine must be declared as dynamic in tbe
program preamble by a statement such as

DEFINE routine n•ne AS A DYNAMIC R#UTINE

so that appropriate flags and loading routines can be created; a


special version of the CALL stacement must be provided to load a
missing routine before calling it if it is not in core; and an out-
of-room error routine must be written to take care of situations
where there is insufficient room to load a routine. Since there is
no special program loading area as there is with overlay, it is pos-
sible that conflicts for core space may occur. Unless the system has
instructions as to which routines it should save when such conflicts
occur, it can do nothing but terminate a program.
If loading is done by programmer instruction, things are simpler.
Statements of the form

IF routine name IS LOADED and


IF routine naie IS NOT LOADED

can test to see if a routine must be loaded before it is called, and


can be used to release other routines, thus allowing room for a new
routine. A statement such as

LOAD routin-e na

can then be used to load the routine into core so that it can be
executed.
If dynamic program relocation facilities are available, they
greatly enhance a programmr's capabilities by providing unlimited
memory capacity for program storage. As vith program overlay, SIN-
SCRIPT II implmntation manuals must be examined to see what particu-
lar features specific computer implementations provide.
-145-

3-06 A SEARCH STATEWENT

In certain types of programs a great deal of effort is devoted


to finding sets of variables that satisfy stated conditions and com-
puting functions of these variables. The FIND statement is used to
search for the first of a set of variable values that satisfies some
logical condition.. The statement

FOR I - I TO N, WITH X(I)*Y(I) > 'IMIT, FIND FIRST.PAIR=THE FIRST I


IF NONE GO TO NO.PAIFS ELSE ...

is a compound statement comrosed of a quaiified POR rhrase and a FIND


statement. The FOR phrase steps the variable ! through the sequence
of values 1,2,...,N, looking for values for which X(T)*Y(I) is greater
than LIMIT. The FIND statement selects the first value of I in this
sequence. The FIND statement further specifies that if no I satisfiez
the "WITH test," th, program branches to the label NO.PAIRS; otherwise,
it continues in sequence after the ELSE statement with the variable
FIRST.PAIR equal to the first value of I for which the test is true.
The above compound statment is equivalent to the program

FOR I - 1 TO N,
DO
IF X(1)*Y(I) IS GREATER THAN LIMITLET FIRST.PAIR-I GO OUT
OTHERWI SE
LOOP
GO TO NO.PAIRS
'OUT'

A FIND statement is always contrclled by a FOR phrase, and can option-


ally have an IF clause following it to direct the flow of control based
on the outcome of the "find." This clause can, be either

IF NONE ataremente ELSE or


IF FCUND ataze',v",re ELSE

If an IF NONE clause is used, the statemn!s foiloving it are executed


if the find iu unsuccessful; if an IF FCUNC clause is used, the state-
ments are executed if the find is successful, In both cases control
passes to the ELSE statement if the IF condition Is nct met. i.e.,
FOUND or not F1¶MOD.
The vorts THE and FIRST are olptiunal after the equals sign at the
-146-

head of the FIND statement, e.g., the statements

FIND MAXI - THE FIRST I


FIND 1AXI - FIRST I
FIND MAXI - I

are equivalent and illustrate alternate forms of the basic FIND statement
FIND variable - arithmetio xpresaeion

If a variable named FIRST is used in a FIND statement, the optional


word FIRST must also bn used to make the statement unabiguous.
Usually, the control variable in the FOR phrase will appear in the
expression. When the first index value is found for which the
logical expression in the FOR phrase is true, the arithmetic expres-
sion is evaluated and its value assigned to the FIND statement vari-
able, which may be subscripted. Thus, in the above example, the value
of the expression I is assigned to the variable FIRST.PAIR when a
value of I is found for which X(I)*Y(I) is greater than LIMIT.
If the last, rather than the first, value must be found, a back-
ward iterating FOR phrase is used. To find the last value of I for
Vhich X(1)'Y(I) is greater than LIMIT, write
FOR I BACK FROM N TO 1, WI)IH X(I)*Y(I) GREATER THAN LIMIT.
FIND LAST.PAIR - I IF NONE. GO TO NO.PAIRS ELSE

This statement is equivalent to the program

FOR I BACK FR)M N TO 1.


DO
IF X(I)*Y(I) IS GREAIER THAN LIMIT,
LET LAST.PAIR - I GO OUT
OTHERWISE
LOOP GO TO NO.PAIRS
IOUT

More than one FOR phrase can be used to control a FIND statement.
When this iL done. the FIND statement is usually written vith a list
of Lw-iable - ritiwatic exressionl phrases, as ina

tIt &lhtnot appear If the arithmetic expression contains a


function whoee implied arSmante are global variables.
-147-

FOR I I TO N. FOR J .I TO MWITH FN(1) FN(J)


F
FIND FS(1) a THE FIRST I AND FS(2) * THE FIRST J
IF FOUND GO TO LABEL(I) OTHERWISE

In cases where there is no expression to compute, a special form


of the FIND statement can be used. This form - FIND THE FIRST CASE -
inhibits the generation of a LET statement to assign the value of the
"found expression" to the "FIND variable." Both of the following two i
statements terminate with the saw value of I:

(a) FOR I-1 TO MAX, WITH V(I)cQQ(I) FIND THE FIRST CASE
(b) FOR 1-1 TO MAX, WITH V(I)QQ(I)I FIND I-THE FIRST I

3-0? A STATEMENT FOR COAPUTING SOME STANDARD


F&WCTIONS OF VARIABLES

Computer outputs often take the form of statistics stmarizing


the behavior of a program. The number of sales made in a particular
weak is a statistic that describes the activity in a store, while
another statistic is the value of the average sale. When information,
such as sales receipts or item invoices, is stored in arrays, or can
be computed by iterating through expressions, the COMPUTE statement
simplifies the task of compiling descriptive statistics.
An example of the use of a COMPUTE statement is:

FOR I - 1 TO N. UNTIL X(I) > 17


COMPUTE MEANX - MEAN.AND MAXIMUNX - MAXIMUM OF X(I)

Like the FIND statement, the COMPUTE statement contains a list


of variables that are met to a computed value after iteration. In
this case the values are specified by statistical names, such as
MEAN and MAXIMUM. In the above exple the logical control phrase
could have selected the individual elements accessed by the loop if
the stetnt were vritten as
FOR I - i TO N0 WITH X(I) > 0 COMPUTE MENX - M•AN,.MAXIMUMX - MAXIMUM
OF x(1)
A COMPUTE statement has the general form:

COMPUTE mompu:4 List OF ari• .tic ezpr~eseson

where compute list is a list of variable and statis'tcal names of the

n -
-148-

form "variable sstatistic none." The optional word THE can be put
before each statistic name, and tb-. word AS can be used in lieu of
the equal sign. A COMPUTE statement can be controlled by more than

one FOR phrase, as in the statement

FOR A - 1 TO N. FOR B - 1 TO M, COMPUTE MN AS THE MEAN OF TABLE(A.B)*LIST(B)

An optional legical control phrase appended to a FOR statement


controls the iteratici sequence or the selection of individual variables,
as shown in the above examples.
When a COMPUTE statement appears within a DO loop with other state-
ments, calculation of computed statistics, such as MEAN, takes place
at the first LOOP encountered. If, for some reason, control is trans-
ferred out of the loop, the statistics are undefined.
In the following example,
computation of the indicated statistics
is executed at the close of the first DO loop. Within the "J" loop
the values of X(J) are summed, and a count accumulated of the number
of X(J) that go into the sum. Before statement4 is executed, these
two values are used to compute MEANX.

FOR I - I TO N. DO
statement 1
FOR J - 1 TO M, DO
statement2
COMPUTE MEANX AS THE MEAN OF X(J)
statement 3

LOOP
statement 4

LOOP

MEANX is undefined within the J loop.


To have a COMPUTE stateownt controlled by several control phrases,
a progrem is written vith ALSO phrases, as:

FOR I - 1 TO N, DO
statement 1
ALSO FOR J - 1 TO M, DO
stat#Aent,
COMPUTE SLJMX AS THE SUM AND "AXX AS THE IAXIPNUM OF X(I.J)
statement 3
LOOP
-149-

1he names that my appear in the statistical list, and their


computations, are shown in Table 3-1.

Table 3-1

STATISTICAL NAMES USED IN THE COMPUTE STATEMENT

Alternative or 1
Statistic Abbreviation Computation
NUMBER NUM Number of items selected in the
NUM
iteration
SUM Sum of the selected values of the
expression
MEAN AVERAGE. AVG SUM/NUMBER
SUM.OF.SQUARES SSQ Sum of squares of the selected values
of the expression
MEAN.SQUARE MSQ SUM.OF.SQUARES/NUMBER
VARIANCE VAR MEAN.SQUARE - MEAN
STD.DEV STD SQRT.F(VARIANCE)
MAXIMUM MAX Maximum value of the selected values
of the expression
MINIMUM MIN Minimum value of the selected values
of the expression
MAXIMUM(e) MAY(e) Value of computed e using the control
variable values that produce the
expression with the MAXIMUM value
MINIMUM(e) MIN(e, Same as MAX(e) but for minimum

The following example illustrates the use of each of these statistics


(assume that an array X in a program has element values as &hown).

N- 5
X(1)- 4.0 X(2) - 7.3 X(3) 12.9 X(4) - 0.5 XC5) - 2.2 X(6)- 7.3

Lot the program contain the statement:

FOR I - I TO 6, WITH (I , N AND X(1) < X(I * 1)) OR I - N,


COMPUTE NX - THE NUMBER. SUMX AS THE SUM, NM AS THE MEAN.
SSQX AS THE SUM.OF.SQUARES, MSQX AS THE MEAN.SQUARE., VARX AS
THE VARIANCE, SDVX AS THE STD.D(V, MINX AS THE MINIw,
MAIX AS THE MAXI"U, MINI - THE 4IN(I) OF X(I)
-150-

The dbove statement iterates the control variable I over the values
1,2,3,4,5, and 6, and selects only those values foe inclusion in the
COMPUTE statement computations for which I < S and X(I) < X(I+1). or
for vhich I=5; thus, it selects X(1). X(2). and X(4) under condition
1 and X(5) under condition 2. For these index numbers, the statis-
tical quantities are computed for the expression X(I). The computed
statistics are:

Coputed
Variable1 Statistic j Computation

NX NUMBER 4
SUMX SUM 4.0 + 7.3 + 0.5 + 2.2 -14.0
MI MEAN 14.0/4 - 3.5
SSQX SUM.OF.SQUARES (4.0)2 +(7.3)2 +(0.5)2 + (2.2)2 74.38
MSQX MEAN.SQUARE 74.38/4- 18.595
VARX VARIANCE 18.595- 3.5 - 15.095
SOVX STD.DEV SQRT.F(15.095) - 3.89
MINX MINIMIM 0.5
PAXX MAX IKM 7.3
MINI MIN(I) 4

3-08 ALPL4--A NEW IE)DE

Since cmpvtteru can manipulate characters as well as numbers, the


ianipulation of arbitrary symbols has become a feature of many pro-
graming languagee. The ALPHA mode defines a vari.able as containing
alphanumiric characters rather than numbers, an alphanumeric character
being a letter, digit. or special symbol such at + ot ?. A c-ruzLar
string is a sequence of ALPHA characters, such aa appear in the follow-
4a4 list:

LIST PART.NUMIER mY NOUSE "**EUREKA****


-) X* Y " Z 1,678,0W0 34.5
fell ......... 23 SKIDOO
Any charerter that can be represented vithin a computer, including a
blank character, my appear in a character strinj. In the above

40.
-15 1-

example, the string MY HOUSE is eight characters long and includes a


blank character.
The number of characters that can be stored in a computer word
varies, as does the number of digits that can be stored in an INTEGER
variable. The number for a specific SIMSCRIPT II implementation is
given in that implementation's instrurtion manual. In all implemen-
tations, however, ALPHA variables are stored in the sam way - charac-
ters are left-adjusted within a computer word. If a single character
i& read into an ALPHA word. it is put in the leftmost character posi-
tion and followed by blanks.
ALPHA variables are declared by statements such as

DEFINE V AS AN ALPHA VARIABLE and


NOMIALLY, MODE IS ALPHA

ALPHA ",artables can be dimensioned, and can be SA.VED or RECUPSIVE.


ALPHA fuactions are also possible. Defining a function am ALPHA meanm
that the "value" returned by the function is treated am a character
string, rather than as a numerical quantity.
ALPHA variables are treated am INTEGER variables in all computa-
tions except input/output. This means that the sum of tvo ALPHA
variables is the (normally meaningless) algebraic sum of their internal
character representations. If X and Y are ALPHA variables and X con-
tains the character string ONE and Y the character string TWO, the
statement ADD X TO Y produces meaningless g4rble; it does not produce
the character string ONE TWO.
ALPHA variables are often used in IF tests to permit input dita
to be readable rather than being mere arbitrary code numbers. If tde
end of a deck of data is to be si"aled b! a flag, it is easier to
understand the organization of the deck if th f"lag is the character
string END than if it were, for instance, the number 999. x*n ALPHA
variable or function can be used in a logical exireseson in either of
two vays: (1) with another ALPHA variaole or function in teots such me

IF INPUT.CHARACTER EQJALS ALPHABET(1) and


WITH VALUE NOT EQUAL SY"W)L

or (2) vilh a !er• in tests such am


-152-

IF INPUT.CHARACTER EQUALS "?" and


WITH VALUE NOT EQUAL "*END*"
A literal, as shown, is a character string enclosed in quotation
marks. A quotation mark within a character string is represented
by an underscore (-). Literals are ALPHA constants. Ttey are com-
piled directly into programs, cannot be altered, and can be used just

like ALPHA variables. Of course there can be no moar characters in


a literal than in an ALPHA variable. Literals appear in examples
throughout the remainder of this section; their utility should be
apparent from their use.
The remainder of this section is concerned with the effect ALPHA
variables have on previously described input/output statements. Their
effect on all other statements has already been discussed, i.e., they
are treated as INTEGER quantities.
In a free-form READ statement of the form READ V, where V has been
declared as ALPHA, reading begins at the first nonblank character and
terminates when the first blank appears or after reading as many
characters into V as it can contain. Successive ALPHA values can be
separated by blanks, as can numbers. Thus, blanks cannot be read into
ALPHA variables by a free-form READ. A number to the right of a full
ALPHA word of characters need not be separated from them by a blank,
although one is certainly permissible. Assume that a computer word
can hold four alhanumeric rharacters and that X is ALPHA and I is
INTEGER. The READ statement

READ X(1),X(2),X(3) AND I

reads the first four contiguous xnonblank characters into X(1), the
second four into X(2), and the third four into X(3), and then reads
into I however many digits follow to the first blank. If the free-
form "look ahead" feature is used (see Sec. 2-13), the wode of the
next value to be read can be ascertained by the statement

IF MODE IS ALPHA
If this value is an integer uumber, it is reported as INTEGER, even
though a string of digits is a legitimate character string. Since

%The single character " used to bracket a literal is different


from the two characters '' used to bracket a comment.
-153-

the system does not know how characters are to be used but only their
form, ti-e value has to be reported as INTEGER.
In a LIST statement of the form LIST V, where V has been declared
as ALPHA, the contents of V are displayed similarly to INTEGER values
except that character strings are left-adjusted. Additionally, lead-
ing zeroes are not suppressed, as they are legal alphanumeric charac-
ters. In ALPHA mode, zero and blank are distinct symbols.
In a PRINT statement where the format of an item must be described
by a "picture" of asterisks, single parallels, and decimal point.s, each
ALPHA character must be pictured. Unlike INTEGERS, where only the
position of the rightmost digit must be shown, all characters of an
ALPHA variable must be indicated either by * or 1. If more characters
than are stored in an ALPHA word are indicated, only the leftmos-:
positions are used. This choice of rules, quite different from the
rules for INTEGER printing, is made to allow the greatest flexibility
in displaying alphanumeric information.

3-09 A FORMATTED INPUT/OUTiPUT STATEMENT

The READ, PRINT, and LIST statements permit programs to (1) read
data in free-form from punched cards, (2) display computational results
in picture-like formats, and (3) generate labeled data displays without
consideration of specific formats or data arrangements. There is much
more to computer I/0 than these facilities, however. For example,
there are other types of input/output units, such as magnetic tapes,
disks, and drums. In addition, there are recognized needs for facil-
ities to read and write formatted data and to transmit information in
internal machine representation as well as decimal format.
This section presents a set of statements for performing input/
output functions with many types of I/O devices. Unfortunately, these
statements can only serve as guidelines for SIMSCRIPT II compiler
implementations, and cannot be taken as strict language specifica-
tions due to the variance in input/output device designs among co'-
puter systems, as well as to the special relationship between input/
output operations and computer operating systems. Specifications
that appear in single statements in our proposal may have to appear
-154-

in two separate statements in some computer systems, We can specify


the conctituents of an I/0 statement and demonstrate its capabilities,
but we cannot ensure that these specifications are compatible with
all computer systems. It will be the task of the individual SIMSCRIPT
II implementation reports to describe the way in which input/output
statements differ from those described here.
In general, three things m=%t be specified when an input/output
operation takes place: a physical device, an information list, and
a format. In the statemeats READ. PRINT. and LIST, a physical device
is Vuplied (card reader or printer), an information list is stated
explicitly, and a format is, in the first instance, "free." in the
second, a "picture," and in the third, standardized. The statements
following provide flexible options for expressing each of these items.

Physical Device Specification

Since data can be read from, or written on, a large number of


data devices of different types, the device to be used in any particular
instance mst be specified. This is done by giving each distinct
device a name or code number. It is difficult to specify the form of
the code as this is an item that differs iong computer systems. For
convenience we will asstme that each device has a device nee abbre-
viated as "d," and leave the precise specification of the form of "d"
to specific implementation manuals. If "d" refers to a number, any
arithmetic expression should be allowed. For example, assume that an
installation has as its input/output devices a line printer, a card
reader, a card punch, six magnetic tape drives, a magnetic drum, and
two disk units. By convention we number (name) these devices 1,2,....12.
respectively. A particular device is selected as a curret input unit
or current output unit by executable staLements oi the form
USE d FOR INPUT or USE UNIT d FOR INPUT and
USE d FOR OUTPUT or USE UNIT d FOR OUTPUT

TAPE can be used in place of UNIT when appli.cable. Such statements


specify that the named devices are to be used in lisically subsequent
input and output statements; that is, since they are executable
-155-

statements, the physical order in which th.ey appear in a program need


not be lmportant; GO TO statements can transfer from USE to READ and
WRITE statements that might phye.caily precede them.
Each time a USE statemnt is executed, a global variable named
READ.V or WRITE.V is assigned the value of the designated unit "d."
These variables can be used freely in all SIMSCRIPT II statements, as in

IF READ - 5, GO TO SWIrCH.UNIT ELSE


When a program does not contain any USE statements, as in Level 1
and 2 programs, SIMSCIPT II "sum that a designated "standard"
card reader and "standard" line pririer are used for its READ, PRINT,
and LIST operations. Among the items of information that must be
specified when a SIMSCRIPT II compiler is used in a specific environ-
sent are the device names of such standard units. READ.V and WRITE.V
are initially set to the values of theme devices.
If the cu rent input unit is specified as the current output unit,
the current input unit is changed to the "standard" card reader. If
the current output unit is specified as the current input unit, the
currant output unit is changed to the "standard" line printer. Since

a device cannot be used for both input and output at the same time,

this ensures that error messages will be properly displayed and in-

creases the chances of catching programming errors in unit assignments.


The READ. PRINT, and LIST statements can, of course, be used with
other units, as well as with the designated standard units. Free-
form data may be read from any one of a nuber of card readers or

magneaic tape units if they are designated as the current input unit,
whereas output can be written onto magnetic tape, as well as being

displayed on printers.

Input/Output Devices

A great many input/outpit devices are available to a computer


user today, but few computer installations have access to all of them.

The devices people are most familiar with and that are found in the
majority of installations are punched card readers and punches, line

printers, typewriters, sagnetic tape transports, magnetic drums, and


-156-

varying form of disk storage devices. Devices less common, although


also widely used, are paper tape readers and punches, cathode-ray tube
displays, light pens, and pressure-sensitive input tablets. Although
SIMSCRIPT II can provide coimands for dealirng with all of these de-
vices explicitly, it does not do so. Rather, it provides a mechanism
for dealing with all devices that read and write information sequentially.
Each device has certain characteristics, and is organized, or
can be organized, in specific ways. SIISCRIPT II utilizes one par-
ticular mode of organization that is shared by all devices, but one
that is by no mans inclusive for all possible organizations. Such
a mode is the sequential classification of a data strean into fields
and record.
A field is a logically defined group of consecutive chatact4re
within a record; it does not necessarily correspond to any physically
distinguishable unit. A format (delineared later in this section)
describes a data field; data fields are defined by formats and. delin-
eated by blank characters in free-form data streams. A record is a
physically distinct sequence of data fields.
Within each STMSCRIFT II program are input and output buffers.
Tnput buffers are filled, and output buffers emptied, by nrogrammer
instructions in READ and WRITE statements, and by the SIMSCRIPT II
system when statements such as PRINT and LIST are used. Individusl
READ and WRITE statements do not necessarily access an entire record,
but proceed sequentially through input and output buffers as data
elements are selected. Normally, a programmer need not concern him-
self with the functioning of input and output buffers except to empty
them by indicating that subsequent input or output operations are to
begin on a no line or card. Folloving subsections describe ho this
is accom1lished.
Because SIMSCRIPT II has facilities for operating on fields and
records and because its source language statements are independent of
particular devices, it has a set of conventioem that define the con-
cepts of field and record for different types of devices. These
devices are shown in Table 3-2. The distinctions showt in the table
will become cisear, fi the statemmets that employ them are dAecribod
-157-

Table 3-2

INPUT/OUTPIYT UNIT CHARACTERISTICS

MaIF m f
!/O Device Field Width Record

Punched nard 80 columns Card


Line printer -b- columna Line
Magnetic tape none -a-
Magnetic drum none -a-
Magnetic disk none -a-
Typewriter -b- columns Line
Paper tape none -a-

aDe-limited by an internal, program-


generated mark.
bDete.-rined by peripheral equipment
characteristi•s.

in the following pages. The statements will also be clarified by the


examples shown at the end of the section.

The Formatted I/O Statements READ and WRITE

The READ statement used thus far has only been able to read free-
form data. A READ statement that accepts formatted data has the form

READ vaina~bZe liet AS foivat 1,ist

in which each variable value to be read has its input data format
described by a corresponding descriptor in a format list. These for-
mats, which are codes telling how the input data are placec on data
cards, are described in the next subsecti..n.
The WRITE statement transfers values frov vit•in the computer to
specified external media, such as line printers or magnetic tapes.
Every WRITE statement is formatted. With the sole exception of the
LIST stetment, it is always the programmr's obligation to indicate
the arrangement of output data. The WRITE statemnt looks like the
READ @tatement; Its form is
-158-

WRITE arith~gtio expresion list AS fo,,aat list

In this statement the indicated expressions are evaluated and printed


in the form described by their matching format descriptors.
Before these READ and WRITE statements can be described through
examples, the format descriptors must be defined. There are ten of
then; five are used for expressing numerical pictures and five are
used for spacing, skipping lines, and similar actions. The five
numerical descriptors, which define integer, decimal, scientific nota-
ties, alpha.umeric, and internal computer representation data fields,
will be described first.

I (Integr) Descriptor

A descriptor of the form n I w is used for converting numbers


from their internal integer computer storage representation to an
external format, and vice versa. The character I is always followed
by an expression (w). specifying the maximam number of digits in the
integer field, including the sign. The I can be preceded by a number
(n), declaring that the descriptor defines n consecutive identical
data fields. The iorlsts 2 I 6 and 14 1 3 define 2 fields of 6
poeitions and 14 fields of 3 positions, respectively. The musnt be
at leapt oneu blank betu~een the fields ni,I, and w.
When an I format is used for input, it specifies that the full
contents of a field w digits wide are to be stored as the value of a
correspeading variable in a READ statement. Blank field positions,
leading, embedded, or trailing, are treated as zeroes. If a field is
unsigned, it is interpreted as positive. although a plus sigv can be
punched. Excepting the sign character, only numbers can be punchad
in an I data field. If w is larger than the maximuim number of digits
that can be stored in a computer word. only the rightimost, storable
digits are used. The additional digits are skipped over. If w is
leos than a "full word." the digits read are right-edjusted and the
word filled out on the left vith zeroes.
On output, an I format places a right-adjusted integer in a field
of specified width. Xvinbera larger than the field vidth are converted
-159-

to scientific notation. Positive numbers are printed unsigned, while


negative numbers have their sign printed to the left of the highest-
order digit. Leading zeroes are suppressed.

D (Decimal) Descriptor

A descriptor of the for. n D(a,b) is used for converting numbers K

from internal to external decimal representation, and vice versa. ,


The 8 field specifies the number of characters in the .ata field,
including the sign and decimal points, the b field specifies the ntum-
ber of digits to the right of the decimal point, and the optional n
Lield specifies the number of consecutive values of the format.
Wien used for input, the D format accepts numbers punched vith

or vithoot decimal points. If a decimal point is omitted, one is


implied before the first digit in the b field. When a decimal point

is present, it overrides the location specified '.y b. Very large and


very small numbers can be input in scientific notation, for when used
t
for input the D and E formats are equivalent.
Used in output statements, D formats describe the precision in
which decimal numbers are displayed. Numbers more precise than their
output formats are rounded, as described in Table 1-2, Sec. 7-13.
Every number output by a D format is punched in a field of a colims:
the first colum is used for the sign, the next a-b-2 columns re for
digits, the next column is for the decimal point, and the remaining b
columns are for digits. The sign is printed if a number is negative,
otherwise it remains blank. If the integer part of a negative decimal
number does not fill up the a-b-2 positions allotted to it, the sign
is shifted to the right, next to the high-order digit. Leading zeroes
are suppressed. If a number has trailing zeroes, aa in the number
10.0, which is vhole-valued, the trailing zeroes are printed. The
trailing zeroes are blank only if the value of a number is exactly
zero. as opposed to a number that has a very small value in the oo.-
puter's internal representation.

See p. 161.
+I
I
-160-

E (Scientific) Descriptor

Extremely large and extremely small numbers, and numbers that


vary widely in scale, can be read and written in a constant field
width by using an E format. This format is similar to the D format
in that it specifies a field vidth and a decimal point position by
the numbers a and b in the form n E(a.b). but it differs from the D
format in having a scale factor field. The scale factor field appears
to the right of a decimal number and indicates the necessary number
of places right or left the decimal point must be moved to convert
the scaled number to its proper form.
The E format is thus equivalent to the D format, plus a scale
factor. Numbers printed or read under E format control are of the
general form

txxx.xxxE±xx

although sow latitude is allowed in vriting the scale factor. A


positive scale factor, such as E+02 or E 7 raises the value of a
printed number -- 24.795E+04 represents an internally stored value
of 24.795 x 10 - 247950. A negative scale factor decreases the
value of a printed number -- 24.795E-04 represents an internally
scored value of .0024795.
The E format can be used for both inpu' and output. When used
for output, it aligns numbers according to the format specification
and prints a scale factor indicating the true value of the printed
number. All E formatted numbers are a print positions vide, vith the
first 4-4 positions used for the number, including its sign and decimal
point, and the last four positions used for the scale factor Etxx.
Positive scale factors print vithout the plus sign, as E 10, E 5,
and E 1. Negative scale factors print the uegative sign after the
a.
" E-10. E- 5 and E- 1.
E formatted input data can be ounched in a variety of vays, as
the scale factor may or may not contain a sign or the letter E. The
numere l.0E405, 1.0EO5, +1.OE 5, and 1.0545 are equivalent input
data representations of "he number t00,.00 under the input format
E(7.1). As shc'rn, either a sign or the letter ( must be present to
separate the number and scale factor fields.
Emphasis must again be directed to the fact that when values are
too large to be printed in their indicated formats, data are displayed
in scientific notation. 'The rules governing this are "e followp:

Widthl Characters Printed Example: nuuber-247.538

2 sign of nwbber E +E
3 sign of nwuber E sign of exponent +E+
4 sign of nwuber E sign of exponent d +E÷2
d- digit if 0 < exponent < 9
a * if exponent > 10

5 sign of nurber E exponent +E•C2


6 sign of nuwber digit E exponent +2L+02

7 sign of nwuber digit.E exponent +2.E+02

8 sign of nwnber Jigit.digit E exponent +2.4E+02


> 9 sign of nwmer digit.additionaZ +2.47E+02
digits E exponent +2.475E+02
+2.4754E+02
+2.47538E+02

Numbers can be punched in scientific notation for free-form as


well as for format-directed input. A number of the form numnber e*xo-
nent is interpreted as a scientific notation input field in free-form
input statements. No blanks are allowed between the nwnber and ezpo-
nent parts of the field. The form of these parts are:

number a REAL or INTEGER constant


exqponent Etxx E is optional
+ is not needed if exponent is positive
examples:
1. 0067E+10 1.00F67+10
9.46755W4, 9.46755E4
40DEI 4.041
9.999-6 9.999E-06
5Mb 5+6

rI
-162-

A %.Aphanumeri ) Descriptor

The alphanumeric descriptor n A w is similar to the I descriptor


in form and action. On input, the contents of a specified field are
stored as the value of a corresponding variable in a READ list. This
variable most have been declared as ALPHA. Since an ALPHA variable
can contain any legitimate characters that can be punched in a card,
including blanks, these punched characters are stcred. L: the number
of characters in the field is loes than the number of characters it
an ALPHA comuter word. the characters are stored in the leftmost
positions in the word, followed by blanks. If more characters are
specified than can be stored, the leftmost are stored and the remainder
skipped over.
When used in output statements, the A format extracts characters
from the leftmost part of an output variable or function. The format
A 1 diaplays the leftmost ciaracter. A 2 displays the two characters
farthest to the left, and so on.

C (Comuter Raprooentation) Descriptor

Few comuterb use decimal notation internally. Most use 'mary


coding schemes that represent decimal numers as secquences of zeroes
and ones. Generally, a group of binary bits constituting a character
in a numer system other than binary or decimal is used as an input/
output character. Be:-uuse strings of such numbers are short, they are
easy tn interpret. The unit on the IBM 7090 clase computers that have
36 binary bits per comnputer word is the octal byte. Each 36-bit word
can be treated as twelve 3-bit bytes that take on the values 0.1.2,3.4,
S.,. and 7.
The formst n C e interprets characters read or written in the
unit of the comute: on wihichi a particular FSISCRIFT II compiler is
iwplemented. The for-tat C 12 an an IBMq 7090 neanx read or write 17
octal. characters; the format C 4 on an [134 340 neana read or witlte 4
hexadecimsal characters. The two, of cosira~,% 2re incomatible - no
so re tk.!n hexadecimal characters can be nt~red in a 3(4 word.
Severthelees, there are timies when internsal representation must be
displayet.. and a machine-dependent format Is roquired.
-163-

Formina Format Lists

Format lists are composed of sequences of format descriptors


separated by coma". During the execution of READ and WRITE state-
mants, format lists are scanned from left to right and individual
format descriptors used as they are needed. With f4e exceptions,
variables being read and expressions being vritten must agree in mods
vith their tormat descriptors. The exceptions are INTEGER and ALPHA
modes that can be used interchangeably; when they are interchanged.
the mode of the format descriptor governs. When a format descriptor
is preceded by a repetition character n, n consecutive READ or WRITE
quantities use the sam format. Some examples of READ and WRITE
statem•ents that use formated data follow:

(a) READ X, ANSWER AND Y AS 1 3, 1 2, 1 2

If ye asiume that data are on punched cards, and the above statement --
the first in a program - starts reading at column one, the value
punched in columis 1-3 is sasitned to X , the value pur-hed in columns
4-5 is assigned to ANSWER. and the value punched in columns 6-7 is
assigned to Y. The data card might appear as

column number
00000ocI1,11...
12345678901234
160 3 8

in which case X-160. ANSWER-3. and Y-9. or. it may appear as

column number
0000000001111.
12345678901234
-336-9

in which case X'-3, ANSWER36. and Y--9. The data aro read saque-
tially. Tht information needed to locale a number and detorwirc6 its
form is contained in the foruat descriptors.

(b) READ X, ANSWER AND Y AS 1 3. 2 1 2

Here, the fornat list is the amea (a) except that the second and
third format descriptors have been combined.
-164-

(c) WkITE X, ANSWER AND Y AS 1 3, 2 1 2


In this exanmple, the values of the expressions X, ANSWER, and Y, are
output in the indicated format. We will assume that the output has
been specified to appear on the standard line printer and thnt this
statement is the ficst to be executed. If the values of X, ANSWER,
and Y are 9, -3, and 0, respectively, the printed line appears as

column number
00000000011111...
12345678901234
9-3 0

Notice that leading zeroes are left blank, but that the rightmost
zero in a zero-valued integer is printed.

(d) READ X,YZ AS 3 D(10,3)


Three decimal fields are specified, the first in columns 1-10, the
second in columns 11-20, and the third in columns 21-30. Assume the
data punched as

column number
000000000111111111122222222223333...
123456789012345678901234567890123...
126.345 -18.62 768954346

The first data field is assigned to X and the decimal point is where
it is expected, in column 7. The second data field is assigned to Y;
here the decimal point is not where it is expected, in column 17.
Therefore, the punched number overrides the stated format, and the
value -18.62 is assigned to Y. A characteristic of the D format is
that it allows itself to be overridden if a decimal point is punched
within a field. If no decimal point is punched, as occurs in the
third data field, its location is determined by the format. In this
call, the value 768954.346 is assigned to Z.

(e) READ X AS D(8,2)

Such a data item might be punched as


-165-

column number
00000000011111...
12345678901234
16.5E 2

The punched decimal point overrides the format. The scale factor
multiplies the resulting number by 10**2 so that the value 1650 is
assigned to X. The flexibility of the decimal format is shown in the

following statement that defines a data card so that a large range of


numbers can be accommodated:

(W) READ X(1), X(2), X(3), X(4), X(5) AS 5 D(10,2)

A data card may appear as

column number
0000000000000000000Z222222222333333333344444444445...
12345678901234567890123456789012345678901234567890...
41.25 19.22E-03 4537992 -167.1

in which case X(1)=41.25. X(2)=0.01922, X(3)=45379.92, X(4)=0.00,


and X(5)--167.1.

(g) WRITE AB,C,D,E AS 2 1 4, D(10,3), E(9,1), I 6

This statement defines output pictures for five expressions -- A to


E. Assume that A and B are INTEGER variables with current values 9
and 132, C is a REAL variable with current value 19.2, D is a REAL
value with current value 8.25, and E is an INTEGER variable with

current value -1863976. The output will look like

column number
00000000011111111112222222222333333333344444444445...
1234567890123456789012345678901234567890123456'7890..

9 132 19.200 8.3E+00-2E+06

Thn output of E illustrates the action taken when a value is too large

for its field. In this instance, a seven-digit integer couIe not be

printed in a six-digit field, and was converted to a six-character

scientific representation. The actual value -1.86397xi06 was rounded


6
to a value thst could be printed 2x10 and would retain the most

significance.
-166-

(h) READ A(1),A(2),A(3) AS 3 A 4

If we assume that the array A has been defined as ALPHA, and that each
computer word holds four characters, the following data will be read
and stored in A(1), A(2), and A(3):

column number
000000000111111111
123456789012345678
INPUT DATA

A(1) contains the characters INPU, A(2) the characters T DA, and A(3)
the characters TA . The charanter denotes a blank.

(i) The above string c characters can be printed by the statements

FOR II TO 3, WRITE A(I) AS A 4 or


WRITE A(1), A(2), A(3) AS 3 A 4

whi•h produce the identical output of

column number
00000000011,11
1234567890123
INPUT DATA

(J) The word INPUT alone can be printed by the statement

WRITE A(1) AND A(2) AS A 4, A I

which produces the output

column number
000000000111
123456789012
INPUT

(k) Let I be an INTEGER variable and A an ALPHA variable. The


statement WRITE I AS I 4 displays the value of I as an integer number.
If I had been assigned the value 138 by a LET statement, the number
138 would be printed. The statement WRITE I AS A 4, bowever, displays
the value of I as an alphanumeric string. Had A been assigned the
value THIS by the statement READ A AS A 4, and then I assigned the
value THIS by the statement LET I=A, the value THIS would be printed.
-167-

Thus far, the examples have pretended that each new READ or WRITE
statement starts at the beginning nf a new data card, line, or record.
This does not always occur. It has been a convenient fiction for the
exposition of format descriptors.
All READ and WRITE statements operate on a continuous string of
characters and only skip to a new data card or output line when so
instructed. Thus, the two statements

READ X AS I 5 READ Y AS D(1062)

read successive fields from the same data card (record). Often, of
course, data are split between data cards, or must be read from dif-
ferent, noncontiguous parts of the same data card. A method of posi-
tioning the current input pointer or current output pointer is needed
to do this. Such pointers are variables that point to the last
referenced columns in the various input and output data streams.
They can be advanceO by the statements START NEW INPUT CARD, START
NEW OUTPUT CARD, and START NEW PAGE, which we have already seen, and
by five nonnumerical formas. These formats can be interspersed
among numerical formats, or they can appear alone in READ and WRITE
statements. Examples of the use of these formats are given following
their description.

B (Beginning Column) Descriptor

This format is used to specify the position in which the first


character of an item of input or output data is found or displayed.
The format B n positions the current input/output device at column n.
When several B format descriptors are used within a format list, they
do not have to appear in ascending numerical order; for instance,
the format B 47, I 10. B 5, D(6,3), B 57. D(7,3), B 20, I 4 prints
a line of the following form:

col 5 col 20 col 47 col 57


ID(6,3) 14 I 10 D(7,3)
XX.XXX ... 'xxXx ... XXXXXXXXXx... XXX.XXX
-168-

S (Skip Column) Descriptor

Spaces may be skipped between output items, or columns may be


skipped on input data cards by specifying, through the S n format,
that n spaces are to be skipped before reading or printing the next
item of data. Skipped positions are left blank on output, while data
punched in skipped positions are ignored on input.

/(Skip to New Record) Descriptor

Thus far, format descriptors have presented conventions for


locating and laying out data within input/output records. There is
an implicit understanding that each format list refers to a single
punched card of information or printed line of output; we are aware
that input/output records change only when a START NEW INPUT CARD or
START NEW OUTPUT LINE statement is executed. Unless this occurs,
statements continue to read from the same card or to print on the
same line. A record can be changed within a format list, however, by
using a / format descriptor. This descriptor may be used repeatedly
within a format list; each time it is encountered it skips a record
on the current input/output unit.

* (Skip to a New Page) Descriptor

This format descriptor is analogous to the / format; its sole


function is to eject a page on a line printer. If used in other cir-

cumstances, as when punching cards, it is ignored.

"(Character String) Descriptor

Constant alphanumeric data can be included in output formats by

using a character string format descriptor. All characters included


between double quotation marks are printed as they appear except for

the underscore, which is printed as ". The spacing of the character

string can be specified by other format descriptors such as B, S.


and /, as well as by blanks within the character string. A character

string cannot exceed the length of a printed line. If a long string


is required, it must be split into two string. separated by a /. Some
examples follow.
w

-169-

(a) READ I AND J AS 1 5,/,l 5


A value for I is read from the first five columns following the
present location of the current input pointer for the current input
unit. A value for J is read from columns 1-5 of the record follwving.

(b) READ I AND J AS B 1, 1 5,/,1 5

The current input pointer is returned to the first column of the


current record. If the pointer is greater than 1, a new record is
not selected; instead, the pointer is moved back. Values for I and
J are then read from the first five columns of this record and the
one following.

(c) READ I, J. K AS 3 D(10,2)./


The above statement establishes a "record-oriented" input format.
Each group of variable values is contained on a different card; after
one group is read, a new card is read in preparation for the next group.

(d) WRITE A, B, C, D, E, F AS I 5,S 50,1 5,/,/,/,/,4 w10O,4)

The statement above writes two integer variables spaced 50 columns


apart in an integer format, concludes this record, bringing the current
output pointer to the head of the output buffer, skips three records,
and writes four decimal values on a second record.

(e) WRITE N AND AVERAGE AS "OF",I 3," TO DATE, THE AVERAGE IS ",0(6,2)
Two values embedded in character strings are written from the
above statement. If writing occurs on a line printer and the current
output pointer is at the beginning of a line, the output looks as
follows for N=97 and AVERAGE-53.287:

OF 97 TO DATE, THE AVERAGE IS 53.29

(f) READ A(1),B(2),A(3),A(4),A(5) AS B 5,1 IOD(7,3),/.B 20.3 1 5

This statement begins in column 5 of the current input unit and


reads two values in integer and decimal formats, respectively, then
starts a new record and reads three integer values starting in column 20.

(g) WRITE AS *./././,/

11
-170-

The above statement starts a new output page and skips four lines.
No output values are transmitted.

Controlled READ and WRITE Statements

Occasionally, it is necessary or desirable to read an array of


values under the control of a READ statement,t as in f
FOR 1-1 TO N, READ A(I)

Here, the free-form READ reads a sequence of values across the current
input record. If, however, values are packed in a format with no
blanks between them, the free-form READ cannot be used. One is
tempted to write

FOR 1-1 TO N, READ A(I) AS 1 4

This would be feasible if the values of A(I) were spaced across an


entire record or limited to one record. If, however, the data are
arranged so that meaningful values are contained only in columns 1
through 60 of a data card, the above statement will read through
colum 60 and take values from columns 61-80. One vants to skip to
a new card upon reaching column 61, but cannot vrite

FOR 1-1 TO N, READ A(I) AS I 4.1

as this reads one value per input record. A new convention is needed.
An expresslon enclosed in parentheses placed before a format list
repeats that format list the indicated number of times and then skips
to a new record. If N-12 and four numbers are to be read per card
from columns 1 through 24, the following statements read 12 values
from 3 cards:

START NEW CAMD


FOR 1-1 TO N, READ A(1) AS (4)1 6

This form may also be used if groups of vartabilu with different for-
mats are in a record. The folioving statewent reads 4 groups of data

tInput of an entire array by use cf its name only is restricted


to the free-form READ statment.
-171-

in the format I 6,D(6,2) from each data card until 2N values have
been read.

FOR 1-1 TO N. READ A(I),B(I) AS (4) I 6,D(6#2)


This repetition facility can be used with both READ and WRITE state-
ments, but it can only be used in statements controlled by FOR phrases.
This particular form of the READ statement asumes that input starts
at the beginning of a data card (record). This is the reason for the
START NEW CARD statement in the foregoing example. The statement car
terminate, of course, with the current input pointer positioned in
the middle of a record. This is a function of the format used.
Similar rules apply to the PRINT and LIST startments, as well as
to all input/output operations performed by the SIMSCRIPT II system.
Output is printed wherever the current pointer points, assuming it is
at the head of a record. After output, the system positica• the
pointer at the head of the next record.

Variable Formats

The use of format descriptors containing expressions as well as


constants is one feature available in READ and WRITE statements that
has not been discussed. Arithmetic expressions can be used to control
field widths in formats for data layout purposes. For instance, a
curve of the function log e(1) using * as a graphical character is
generated by the statesen: shown below.

FOR I1- TO 100, WRITE AS B LOG.E.F(I)."*".!

Table 3-3 indicates where expression, can be used Ln format descrip-


tors and states their form. This feature allows formats to be con-
structed during program execution, freeing programs from particular
data forum. Constants defining a format can be read in, perhaps in
free-form, before a deck of data cards, to specify the form in whic"
the data appear. If a program reads In sets of data cards that are
grouped three item to a card with the first item being INTEGER and
the balance REAL, the initialization routine of the program could con-
tain the free-form READ statement
-172-

Table 3-3

FORMAT DESCRIPTOR FORMS

Format Descriptor I[General Form

Integer field I I e
Decimal field i D(e,e)
Scientific field i E(e,e)
Starting column B e
Space skip S e
Alpha field i Ae
Computer rep-field i C e

NOTE: i is an INTEGER constant;


e is an arithmetic expres-
sion.

READ C1, C2, C3, C4. C5

and the program could contain the formatted READ statement

READ 1, A, B AS B C1 , I C2 , S C3 ,2 D(C4,C5)

and the program's dat4 deck might look like

column number
00000000000000000022222222223333333333...
123456 7890123456 78901234567890123456 78...
6 4 10 5 2
342 16.25 1.5
-10 0.5 73.4

Local Input/Output Unit Specifications

We have at this point exasined all but one of the variations of


the READ and WRITE statements. The final feature is the ability to
locally override current input and current ou~vut unit specificationa
declared in USE statements. This facility is provided by the phrase,
USING d, vhich mav be attached to any READ or WRITE statement, as in
the statements

READ I, J A1D K AS 1 6./.2 1 3 USING N


WRITE AS * USING 7 'SKIPS TO A NEW PRINTER PAGE
WRITE IDENTIFICATION AS *.1 7,,1,/1 USING 4+2
READ X USING TAPE 12
-173-

This phrase sets the current input or output unit to the indicated
unit dur'Ang the statement's execution, and returns it to its previous
value on its completion. The optional words TAPE or UNIT can be
written before the unit number, if desired, as in the last example.

A Final Remark

As a final remark, we explain a programaing convenience that can


shorten the number of symbols necessarily written when several state-
monts contain identical format lists or suilists. The DEFINE TO HEAN
statement may be used to define format strings and to call upon them
"by name" in the following way:

DEFINE INTEGER.LIST TO MEAN 1 2,2 I 3


READ A,B,C AS INTEGER.LIST

WRITE IJK,L,M AS INTEGER.LIST, 2 1 10

The first statement is compiled as

READ ABC, AS 1 2,2 1 3

and the second a m


WRITE IJ,K,L,M AS I 2,2 1 3,2 1 10

This is but one of many uses of the DEFINE TO MEAN stateawnt.

.€-:) .¥rS'7A'LLA.v/K2U L'V P'~T/Y•T•' :-T2TrKJ'..S A.V2 FAC.::rTrE:

As described in Sec. S-'-9, data ca.- be orjanized into fi-Ids and


into records. Files are often used in asgnetic tape applications,
and features art present in SI.VEltIT II to assist In 01otr use. The
statewnt CLOSE -, puts an , ,r;-r
--.z-- on tte -,.irrent output

unit. The statements

ADVANCE e INPUT FILES BACKSPACE e INPUT FILES and


ADVANCE e XTPUT 'iLES BACKSPACE e OCJTPUT FILES
-14-

move the current input or output unite forvard or backward the indi-
cated n-mbtr of files, i.e., past a end-of-file markers. The statement

ADVANCE I INPUT FILE

eaves 4 unit to the beginning of the next file, in position to read


the first record in the file. The statements

ADVANCE e INPUT FILES USING c! BACKSPACE e INPUT FILES USING d


ald
ADVANCE e OUTPUT FILES USING d BACKSPACE e OUTPUT FUIES USING d

are available.
The CLOSE. ADVANCE, and BACKSPACE statements clso allow an optional
word before the device specification, as in

CLOSE TAPE K
ADVANCE 2 INPUT FILES USING NMIT 7

Whenever a READ statememt is executed, there is a possibility of


running off the end of a data file. When dealing vith cards, this is
ctntsommt to running out of data, when dealing with tape it is equiva-
lent to running intoaen end-of-fiL.e marker. The free-form READ state-
sent, as pre-Acusly noted, provides a check ior an end-of-file condi-
tion through the statement IF DATA. IS ENDED. A similar check is needed
for formatted I/O, and this is prcvided through a global variable an•
a system action, rather than through a specirl statement.
The automatically defined global variable EOF.V is initialized
to zero vhen * SI'SCRIFT II program •s begun. A programer can leave
the variable alone or set it equal to I in a LET statewenz. When an
end-of-file markir is encountered bv a READ staement, the SISC!IPT II
system refers to EOF.V for action direction. If EOF.V-0. r-ading the
end-of-file marker is considered at% error, and tht prol-a terminates
with on error message. if EOf.V-I, the variables in the READ list are
assigned values of zero, EOF.V is &st to 2, and control returha to the
statement following the READ. In other verde, a value of E0F.V0) is
considered a mesage to the 0I.6CRIIT 11 system that says, in 'ffect.
"Do not terminate my program; rotuin zero values and let aw knot that
I have eacountered an end-of-file msarker.- 0 testing EOF.V after a
READ stalleemna., a progrm r can determine whetheL the statement read
-175-

true data values or encountered an end-of-file marker. This facility


can be used in the following ways:
(1) As an end of data signal:

'READ' READ X AS 1 2 USING TAPE 6


IF EOF.V - 2, GO TO FINISH
ELSE ADO X TO SUN ADO 1 TO COUNTER
GO TO READ
'FINISH' WRITE COUNTER, SUM/COUNTER AS "THE AVERAGE OF",
I 4,"ITEMS PROCESSED IS".O(b,2)
STOP END

(2) To transfer to an error routine rather than terminate:


READ X AS 0(10,3)
IF EOF.V - 2, GO TO ERROR.PRINTOUT ELSE

3-10-2 Positioniin~g Tapes, Die ke, and Dw

A device that his been read from, or written on, is repositioned


at its starting point by the statement

REWIND d
The words TAPE and UNIT are optional aftei REWIND. After a unit has
been rewound, it muat be "used" before it can be read from or vritten
on again. A REWIND comand before a unit has been "used" is ignored.

..- 20-3 rnp•t/Output of No--'-.4 :t ; nfo,',tioo

When information is used only for transmission between computers


or is saved for subsequent resubmission to a working program, it need
not be converted from its internal computer rep:esentatton to "human-
readable" form. A much more efficient direct transfer of informatlon
can be obtained vithout formatting through the statements

READ " Zxa, AS BINARY and


WRITE w*"vwz*h,, e.xrrve.'z
. e: AS BINARY

vhpre a current unit is implied. or QLCUlrh the statement*

REAC , ;: AS BINARY S!NG d and


WRITE er•ee;,; "is!wt:.,
e AS BINAIR LSING d

were a unit Is specified. These starem•nts are especially useful


for storing intermediate results too voluminous to keep in cc-, cm
-176-

tape, or disk, and for reading them back when they are needed. Binary
and formatted data can.not be written together on the same device. The
foliowlng program shows how to save a computed array, release it for
other use, and, at a later time, reuse the array values:

PPEAMBLE DEFINE ARRAY AS A 2-DIMENSIONAL ARRAY


NORMALLY, MODE IS INTEGER
END

MAIN
READ N "FREE-FOPM READl
RESERVE ARRAY(*,*) AS N BY N

computations assigning valuea


to the elements of ARRAY

FOR I=1 TO N, FOR J;-1 TO N, WRITE ARRAY(I,J) AS BINARY USING TAPE 1


,REWIND TAPE 1
RELEASE ARRAY(*,*)

statements that use the released


memory space and then give it up

RESERVE ARRAY(*,*'* AS N BY N
USE TAPE 1 FOR iHPUT
FOR I=1 TO N, FOR J=1 TO 0, READ ARRAY(I,J) AS BINARY

additional computations and output

STOP END

* 3-1 1 INTERNAL EDITING OF INFORM64TION

Mhe SIMSCRIPT II system has one buffer for each input/output


device. The size of each buffer varies, depending upon the use of
the unit (input or output, formatted, or free-form) and the medium
-177-

used (cards, tape, printer). All reading and writing occurs through
these bufters. Both the curient input pointer (RCOLUMN.V) and current
output pointer (WCOLUMN.V) travel along the buffers, point to the last
accessed character, and read or write physically when a / format is
encountered or the end of a buffer Is reached.
The current output buffer is called OUT.F, and can be accessed
as an ALPHA function. OUT.F(1) refers to the first character in the
buffer, OUT.F(1O) to the tenth characterp OUT.F(132) to ,-: last
character. tAs a computer word contains more than one alphanumeric
character and the OUT.F function returns only one character, the value
of OUT.F is a left-adjusted ALPHA word; e.g., if the first buffer
position contains the letter A and each word can hold four ALPHA
characters, the value of OUT.F(1) is A._..tt It is possible to edit
output information by inserting alphanumeric or numeric data directly
into the buffer. When a new record is begun, by either a START NEW
statement or a / format descriptor, the buffer is emptied and filled
as the ensuing formats dictate. Thus, the statement

WRITE X AS /,"THE BUFFER CONTAINS",I 3," CHARACTERS"

empties the buffer (OUT.F(1) through OUT.F(132) now contain blanks)


and inserts the characters THE BUFFER CONTAINS In OUT.F(1) through
OUT.F(19), the value of X in OUT.F(20) through OUT.F(22) and the
characters .CHARACTERS in OUT.F(23) through OUT.F(33). To change the
buffer so that the string reads THE.BUFFER.CONTAINS.33.CHARACTERS
j(assume X=33), one could write the program
t FOR I=1 TO 131, UNTIL OUT.F(I)=" " AND OUT.F(I+I)=" "
DO IF OUT.F(I)=" ", LET OUT.F(T)="."
ELSE
S~LOOP

o', on realizing that WCOLUMN.V points to the last character written


into the buffer, one could write

tAssuming an output buffer of 132 characters.


t In this section a blank character is represented by an underscore.
!I

-178-

FOR I"1 TO WCOLUMN.V,


DO IF OUT.F(I)-" " LET OUT.F(I)="."
ELSE
LOOP

If numbers representing dollar amounts are written, dollar signs


($) can be put before the first digit of each number in a similar way:

FOR 1=1 TO WCOLUMN.V,


00 IF OUT.F(I)-" " AND OUT.F(I+1),-'" ",
LET OUT.F(1)=3$",
ELSE
LOOP
A special internal buffer called THE BUFFER can be used for data
editing with READ and WRITE statements. The length of THE BUiFER is
specified by the system global variable BUFFER.V. Space is allocated
to THE BUFFER by the statements
USE THE BUFFER FOR TNPUT and
USE THE BUFFER FOR OUTPUT
or the statements

WRITE ex'pression list AS forrat list USING THE BUFFER and


READ variabZe list AS format list USING THE BUFFER
BUFFER.V has a default value of 132. It can be set to a different
value before its first USE.
The examples below illustrate how mode conversion is executed in
the internal buffer.

(1) In this procedure, X is an INTEGER variable and A is ALPHA,


X-lO0, and each ALPHA word can hold four characters; the initial
value of A is irrelevant.

WRITE X AS /, 1 4 USING THE BUFFER


This statement sets the internal buffer to:

1 2 34 5 . ......... 131 132

Note that / clears THE BUFFER and sets the current output pointer to
its first position. The statement
-179-

READ A USING THE BUFFER

executes a free-form read from the internal buffer, left-adjusting the


value read so that the stored value of A looks like

(2) If the initial characters of four ALPHA variables are to be


merged to form a new ALPHA value, one can write

WRITE A(1),A(2),A(3),A(4) AS 4 A 1 USING THE BUFFER


READ NEW AS A 4 USING THE BUFFER

3-12 WRITING FORMTTED REPORTS

The PRINT statement that we have been using since Sec. 1-12 has
functioned as both a simple mechanism for displaying short error mes-
sages and as a more complex report layout statement (Sec. 1-16-2).
This section adds two phrases to the PRINT statement and introduces
two control statements to provide a full-fledged report generator
capability.
These new features permit a programner to specify the layout of
printed results, to control the printing of headings and titles, to
eject pages between various report sections, and to arrange "wide
reports" on standard-width paper. Figure 3-1 illustrates the kind of
complex report that can be generated.
The statement BEGIN REPORT marks the start of a report section
within which various kinds of control can be exercised. A report
section, like a routine, is terminated by an END statement. The
statements

BEGIN REPORT
FOR 1=1 TO N, PRINT 1 LINE WITH I,X(1) THUS

END

illustrote a simple report section that merely marks off a controlled


output statement. The report section prints N lines containing two
values each. If the output is to be labeled, the program can be
written as
-180-

0000 000000000 00 0000 0 00000000


00000000000 0 0

I-I
Szz
xX x Ih x Cm

Vi

w . .. . . .. .. .... ... . ... w . ..


I a n

4J

o0000000000000
* XX 000 0000000000000 0 0 000000000 -*S
0000000000000000
C, "I O.. 1
4-)
C

* ..

a.-

°S-

.40 Pdif
-. 4 44
- a w

*
aOo oO XX K *i XX
OOOOOOOOOO000K
0 0 4 *l XX
0000000a000000 XX]• 0- r

000000000 000000 0 000000000000000 0000000000 0 0 0000

5-I.- C-

0- ul
4.. .. .0 ow J- y.. .0 0d g . . .0c49
0.4 I-- a0

04., 2 ... owE - .. .. . .. oo2w •


to In•q 0 4" "* w*6A
0 00 0 0 0 0 0 O 0 0 0 0 000 0000 O 0 00 0 0
-181-

BEGIN REPORT
PRINT I '.INE AS FOLLOWS
I X(I
FOR 1=1 TO N, PRINT 1 LINE WITH IX(I) THUS I
END

This prints a heading above the N lines of output that identify the
displayed values. If N is large and the output continues on more
than one page, only the results on the first page are labeled. All
other pages are untitled.
A heading section may be defined within a report section so that
titles are printed and any necessary computation performed whenever
a page is ejected. A heading section is started by the statement
BEGIN HEADING and ended by the statetient END. All statements between
a BEGIN HEADING and its matching END are executed whenever a page is
ejected by an output statement within an enclosing report section,
but after the heading section itself.
To title all pages of output in the foregoing example, the program
can be written as

BEGIN REPORT
DEGIN HEADING
PRINT 1 LINE AS FOLLOWS
I X(1)
END " HEADING SECTION
FOR 1=1 TO N, PRINT I LINE WITH I, X(T) THUS

END

The statements in a heading section are executed the first time


they are encountered and thereafter every time a page is changed.
Pages are changed whenever the current line count exceeds the number
of printed lines a page can contain. The system variables LINE.V
and LINES.V have the values of the current line count and the permitted
number of lines per page, respectively. LINE.V is initialized to 1
when an output device is first USED; it is stepped from 1 to the cur-
rent value of LINES.V each time a new line is printed. A separate
count of LINE.V is kept for each output device. LINES.V may be changed
by a programmer at any time to vary the number of lines that appear
on each output page. The SIMSCRIFf II system automatically sets
LINES.Vf 55 at the start of each program's execution.
-182-

Pages are numbered sequentially, beginning with 1, with the num-


ber of the page currently beiug written contained in the system vari-
able PAGE.V. As with LINE.V, a separate count of PAGE.V is kept for
each output device. PAGE.V may be reset at any time. When this is
done, numbering continues in sequence from the new value. PAGE.V and
LINE.V always refer to the current output unit.
Within a heading section, the statement

IF PAGE IS FIRST
may be used to select atatements to be executed only on the first page
of a report section's output. The following program illustrates one
way of using the report facilities described thus far:

PREAMBLE
NORMALLY, MODE IS INTEGER
END

MAIN 'DATA' READ LINES.V, N, UNIT


IF LINES.V IS NOT ZERO, CALL DISPLAY(NUNIT)
GO TO DATA
ELSE STOP
END
ROUTINE TO DISPLAY (MU)
USE U FOR OUTPUT
LET PAGE.V- 1
BEGIN REPORT " SECTION
BEGIN HEADING " SECTION
IF PAGE IS FIRST,
PRINT 1 LINE AS FOLLOWS
TABULATION OF MATHEM,ATICAL FUNCTIONS
SKIP 3 OUTPUT LINES
REGARDLESS
PRINT 1 LINE WITH PAGE.V AS FOLLOWS
PAGE NO. **
SKIP 2 OUTPUT LINES
PRINT 1 LINE AS FOLLOWS
I SQRT(I) I SQ LOG(I)
SKIP 1 OUTPUT LINE
END "HEADING SECTION
FOR J- I TO M, PRINT I LINE WITH J,
SQRT.F(J), J**2,LOG.10.F(J) THUS

END " REPORT SECTION


END " ROUTINE DISPLAY
-183-

The above program (1) in its MAIN routine reads in control infor-
mation and (2) in its DISPLAY routine uses a report section to prepare
a labeled output display. The variable LINES.V is used both to control
the number of lines prinead per page in successive reports and to
terminate the program.
Within the routine DISPLAY, an output unit is selected outside
the report section &nd PAGE.V is set to 1. This enables each report
to be printed on a separate device, if desired, and sets the number
of the first page of each report to 1. Within the report section
SKIP statements are used to separate heading information.
If the data read by this program are the sequence of values 50,
100, 5, 20, 40, 6, 0, 0, 0, two reports vll be printed. The first
will display the values of J, vj, j2, and log(j) for J-1,2,...,100 on
three pages of output unit 5. If we assume that printing starts at
the top of the first page, it vll contain the heading TABULATION OF
MATHEMATICAL FUNCTIONS, the page number, the heading I SQRT(I) I SQ
LOG(I) and values for J-1,2,...,41. The second page wvii contain the
page number, the heading I SQRT(1) I SQ LOG(I) and values for j- 42,
44, ... , 86. The third page will resemble the second, except that it
will contain values for j - 87,89, ... , 100.
The second report will be similar to the first, except that it
will display values for j - 1, 2. ... , 40 on pages that contain only
20 lines. The heading TABULATION OF MATHEMATICAL FUNCTIONS will be
printed on the current page, renumbered 1, of output unit 6.
Whenever it is necessary to begin each report section on a new
page, as might be done in this example, the BEGIN REPORT statement
can be written as

BEGIN REPORT ON A NEW PAGE

which ejects a page on the current output device unless the current
page has not been written on (LINE.V- 1, WCOLUMN.V- 0). This prevents
blauk pages from being ejected between renorts.
The form of a "typical" report using the statements described
thus far is
-184-

BEGIN REPORT ON A NEW PAGE

program statements

BEGIN HEADING

IF PAGE IS FIRST, ... ELSE

SKIP N LINES

END"HEADING

program sto.tements

END"REPORT
wit! the variables LINE.V and PAGE.V being used in computational,
decisionmaking, and output statements. PRINT statements appear in
heading and report sections, and usually are controlled by FOR or
WHILE statements in the part of the report section labeled "program
statementa." The flow of control in a report section such as appears
on this page is as follows:

(1) Execute statements between BEGIN REPORT and BEGIN


HEADING, if any;
(2) Execute statements in the heading section, if any;
(3) Execute statements between END"HEADING and END''
REPORT if any, executing statements in the heading
section every time a page is changed.

Theae statements are adequate for many reports. A report for


which they are not suited is one that must print more than 80 coluams
of information per line. Adding the word DOUBLE to a PRINT statement
in the following way
-185-

PRINT i DOUBLE LINES WITH expzession liet THUS

specifies that 2i, rather than i, format lines follow that are to be
read in pairs and interpreted as one format line 160 columns long.
To fill an entire line on a printer 132 columns wide, one would write
a statement as

PRINT I DOUBLE LINE AS FOLLOWS


AA.AAAAAAAAAAA....................... ............ AAAAAA
AAAAAAAAAA ............... AAAAAAAPA
The first format card has an A punched in each of its 80 columns; the
second format card has an A punched in its first 52 columns. "Double
width" PRINT statements are not restricted to report sections. Any
PRINT statement can be expanded to double width.
The inclusion of an optional clause in the BEGIN REPORT and
PRINT statements adds one more important report-generation feature.
Figure 3-2 shows the kind of report the clauses handle, reports that
have rows of data with more items in each row than a single page can
contain.
In preparing reports of this kind, a series of pages is printed
with different column indices. In Fig. 3-2, pages 1 and 2 are printed
with column indices ranging from 1 to 50, and pages 3 and 4 are printed
with column indices ranging from 51 to 100. This feature, specifyLig
an iteration sequence for column indices and having pages printed
that, when separated and put together side-by-sida look like printing
on a wide page, is known as otowm, repetition. It is specified by
an optional clause in the BEGIN REPORT statement

BEGIN REPORT PRINTING for IN GROUPS OF e PER PAGE

The word for represents a FOR. WHILE, or UNTIL statement, perhaps


qualified, that generates column indices. The arithmetic expression
e specifies the number of indices in this iteration sequence to be
used on each page. Thus, the statement

BEGIN REPORT PRINTING FOR I - 1 TO 50 IN GROUPS OF 10 PER PAGE

specifies that five sets of column indices will be used for five ex-
ecutions of a report section. The report soction vill be executed
-186-

PA Gi PA CE3

1 2 3 4 .......... 50 51 52 ........... 100


1 1
2 2
3 3
4 4
5 5
6 6
7 7

PAGE 2 PAGC 4

1 2 3 4 .......... 50 51 52 ........... 100


8 8
9 9
10 10
11 11
12 12

Fig. 3-2 -- A report using row and column repetition

first with I- 1,2,3,4,5,6,7,8,9, and 10; second with I- 11,12,1...,20;


... ; and fifth with 1. 41,42,...,S0. The index values Are LtOt gIven
to the report section individually, but in groups that are used all
at once by a epecial version of ti-e PRINT statement.
If a controlling for phrase in a BEGIN REPORT statement is emptN,
i.e., produces no values, the e*tire report section headed by this
statement is skipped, e.g., FOR 1-1 TO 4. WITH X(I) . and no X(I)
is greater than 0.
The groupi of iteration values are used in a PRINT statement by
a clause specifying that a group of values are to be printed using
-187-

the indices generated by a preceding BEGIN REPORT statement. The


following example Illustrates ore such use:

BEGIN REPORT PRINTING FOR J- 1 TO 25 IN GROUPS OF 5


PFR PAGE
BEGIN HEADING
PRINT 1 LINE WITH A GROUP OF J FIELDS THLS

SKIP 1 OMJTPUT LIKE


END HEADING
FOR I- 1 TO 6, PRINT 1 LINE WITH A GROUP OF
X(I,J) FIELDS THUS
ert ** 0* •/* 0'

END REPORT

This program generates four pages of ourput. Page 1 uses the first
five values of J. A headilug displays the values of J. and a row
repetition statement prints the values of X(IJ) for those values of
J and 1- 1,2,3,4,5,6. Fii.:re 3-3 illustrates how such a page might
appear.

1 2 3 4 5

Fi. 3-3 Cor•u' repetition,

Pg 3. 4.andia.
ae 0 p-u

Fage
2. Fig. 3-4~ir.lok eatlly.' !iko
kt page I nfrm i

SFig.
3-3 -- Columnw repetltlofl,

i ~ Fage 2, tig. 3-4, looks exactly .like page 1 in form, but jeots

the second five values of 2 to select values for display.


Palr.. 3, a. and S are similar. vith pag~e 3 using J'1I,...,.1",

and pig. 4 ue!ng J0 16,...,.M, etc.


The phrase A GROUP OF UELDS In a 'NINT acat'mait notifies the
compiler that a sequence of index values generated for the enclosing
-187-

the indices generated by a preceding BEGIN REPORT statement. The


following example illustrates one such use:

BEGIN REPORT PRINTING FOR J, 1 TO 25 IN GROUPS OF 5


PER PAGE
BEGIN HEADING
PRINT I LINE WITH AtGROUP OF J FIELDS THUS

SKIP I OUTPUT LINE


END HEADING
FOR I- 1 TO 5, PRINT 1 LINE WITH A GROUP OF
X(I j) FIELDS THUS
REPO.i S~END

This program generates four pages of output. Page 1 uses the first
five values of J. A heading displays the values of J, and a row
repetition statement prints the values of X(I,J) for those values of
J and 1- 1,2,3,4,5,6. Figure 3-3 illustrates how such a page might
appear,

1 2 3 4 5

** ** ** ** **k

Fig. 3-3 -- Column repetition,


page 1

Page 2, Fig. 3-4, looks exactly like page 1 in fo.-m, but uses
the second fi';e values of J to select values for display.
Pages 3, 4, and 5 are similar, with page 3 using J1ll,...,15,
and page 4 using Jz 16,...,20, etc.
The phrase A GROUP OF FIELDS in a PRINT statement notifies the
compiler that a sequence of index values generated for the enclosing
-189-

All repeated formats need not be identical, e.g., and but they
must be of the same mode.
If it is not necessary that each set of column repetition groups
start on a new page, the PER PAGE clause may be omitted from the
BEGIN REPORT statement. The following report section uses this fea-
ture to display a matrix containing more columns than can be put on
one line:

FOR I=1 TO N, DO
PRINT 1 LINE WITH I AS FOLLOWS
ROW ** i
BEGIN REPORT PRINTING FOR J= I TO M IN GROUPS OF 24
PRINT I LINE WITH A GROUP OF X(IJ) FIELDS THUS
END''REPORT
SKIP 2 LINES
LOOP
Such a program produces a report that, for M= 50, looks like Fig. 3-5.

ROW 1

* ** ** ** * * * *** ** * ** * *

*** * * * ** * * * * *

Fig. 3-5 -- An example of column repetition

Note that the total number of column indices generated need not be an
even multiple of the group size, e.g., 50 and 24 above.
A final feature makes it possible to generate attractively labeled
reports that have row, as well as column, sunmarizations, even if the
reports use column repetition. This is done by adding a clause to
tLe PRINT statement that suppresses some output until all column
-190-

repetition data have been printed. A typical statement using this


feature will look as follows:

BEGIN REPORT PRINTING


FOR J- 1 TO M IN GROUPS OF 10 PER PAGE
PRINT 1 LINE WITH A GROUP OF X(I,J) FIELDS,
SUMX(I) SUPPRESSING FROM COLUMN 70 AS FOLLOWS
t
Column 70

If M=30, three sets of column indices will. be generated; the above


format line will be repeated three times, on three separate pages.
Only on the last page, however, will the last format be used, and
the value SUMX(I) printed. The SUPPRESSING clause specifies that
all formats from column 70 on are to be inhibited until all column
index values have been used. This includes both data and textual
material. The three pages printed by the above statements are shown
in Fig. 3-6.
The program in Fig. 3-7 generates the report shown in Fig. 3-1
and illustrates the statements of this section. The program is shown
as it would appear on punched cards. When writing reports, wider
paper is recommended. Double-length formats can be written across
a page and cards punched from them.
P
-191-

Page 1

Page 2

Page 3

Fig. 3-6 -- An example of format suppression

I,
-192-

Card Column

OOOOOOOOljllllllll2222222222333333333344444444445555555555666666666677777777778
12345678901234567890123456789012345678901234567890123456789012345678901234567890

LET PAGE.V=1
BEGIN REPORT ON A NEW PAGE PRINTING FOR DEPOT=1 TO 60 IN GROUPS OF 24 PER PAGE
BEGIN HEADING
PRINT 1 DOUBLE LINE WITH PAGE.V AS FOLLOWS

PAGE *
PRINT 1 LINE AS FOLLOWS
DEPOT TO BASE SHIPMENTS
SKIP 1 OUTPUT LINE
PRINT I DOUBLE LINE WITH A GROUP OF DEPOT FIELDS SUPPRESSING FROM COLUMN 91 THUS
DEPOT ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
TOTAL
PRINT 1 LINE AS FOLLOWS
BASE
END '"HEADING
FOR BASE=1 TO 120, PRINT 1 DOUBLE LINE WITH BASE, A GROUP OF SHIP(BASE,DEPOT)
FIELDS, TOT(BASE) SUPPRESSING FROM COLUMN 92 AS FOLLOWS
•** * * * * * * * * * * * * * * * * * * * * * * * *

SKIP I OUTPUT LINE


PRINT 1 DOUBLE LINE WITH A GROUP OF SUM(DEPOT) FIELDS, GRAND SUPPRESSING FROM
COLUMN 92 AS FOLLOWS
TOTAL ************************************************

END

Fig. 3-7 -- A report generator program


I)
-193-

Chapter 4

SIMSCRIPT IT: LEVEL 4

4-00 INTRODUCTION

Thus far we have dealt with an algebraic language. While having


features that Pre clearly noncomputational, such as ALPHA mode, the
majority of the statements have had a computational or input/outut
flavor. This section adds a new dimension to SIMSCRIPT tI by providing
language statements that are (1) oriented to problem definition and
modeling, and that (2) manipulate data structures more complex than
simple variables and arrays.
The section is roughly organized into three parts: definition,
organization, and maaipulation. First, definitions are provided for
the three constituents of the SIMSCRIPT II world view: entities,
attributes, and sets. Next, the relationships between these constitu-
ents are discussed, with special mention made of how they are organized.
Finally, statements that use these constituents to perform particularly
useful functions are presented.

4-01 ENTITIES AND ATTRIBUJ!"S

While subscripted and unsubscripted variables are adequate for


moat procedural programming problems, e.g., algebraic calculations
for scientific and business applications, vartables are inadequate
as basic language constructs for a large class of modeling problems.
The inadequacy stems from two sources: (1) the need for more organiza-
tional structure than simple arrays afford, and (2) the lack of clarity
of programs written within the descriptive 1imits of variable name and
-194-

subscript expression conventions. While the first limitation is


certainly the stronger, insofar as inadequate structure imposes con-
ceptual limitations, the benefits of descriptive notation cannot be
minimized. SIMSCRIPT I provides needed structure and narrative
clarity through statetments that define and manipulate entities,
attributes, and sets.
An entity is a program element, much like a variable, that existo
in a modeled system. It is like a subscripted variable in that it
has values, called attrbutesa, associated with it that, %hen assigned
specific values, define a particular configuration or state of the
entity. Urlike subscripted variables, entities have their attributes
named, not numbered, enhancing model description. For example, in
Levels 1-3 a collection of ten men having the attributes of age, num-
ber of dependents, and social security number may be described by a
two-dimensional array defined as follows:

RESERVE MAN AS 3 BY 10

with the understanding that MAN(I,4) represents the age of the fourth
man, MAN(3,b) the social security number of the sixth man, etc.,
according to the layout:

1 2 3 4 5 6 7 8 9 10
AGE 1
DEPENDENTS 2
SOC.SEC 3

Level 4. however, permits the entity MAN to be defined hy the statesent

EVERY MAN HAS AN AGE, A NUMBER.OF.DEPENDENTS


AND A SOCIAL.SECURITY.NUIMBER

end a particular man's attributes to be accessed by references such


as AGE(MAN) and SOCIAL.SECURITY.NUMBER(MAN). A pa&ticular man Is
specified by the value of the variable MAN. Thus, the EVERY statemnt
defines a otaes of bject.e, each called MAN, having similar properties.
Every MAN, of which there may be many, has the sa attributes.
-195-

Entities and their attributes are declared in a program preamble


by statements of the general form

EVERY entity no= HAS AN attribute nem Zist

Entity and attribute names follow the sa naming convention as vari-


ables and routines and each variable, entity, attribute, and routine
name must be unique. To assist in the creation of readable programs.
the words As THE, and SOME can be used in place of AN, as in

EVERY MAN HAS AN AGE, SOME DEPENUENTS AND A


SOCIAL. SECURITY .NUMBER

Entity declarations implicitly state that attributes occupy specific


locations in entij. records. The above declaration states that the
value of AGE is to be found in word 1 of a MAN record, the value of
DEPENDENTS in word 2. etc. Each MAN record can be pictured as

MAN

value of AGE
value of DEPENDENTS
value of SOCIAL.SECURITY.NUMBER

and the form AGE(MAN) can be translated into "the value found in the
first word of the record indexed by the value MAN." Since attribute
names specify relative Zocations of values in entity records, no two
entities can have an attribute with the asme name placed in different
words within the two entity records. The statesents

EVERY W1ANHAS AN AGE


EVERY WOMAN HAS AN AGE

specify a co'mon attribute, AGE, correctly; the statements

EVERY WiN HAS AN AGE


EVERY WOMAN HAS SOME DEPENDENTS AND AN AGE

do not. Sections 4-03 and 4-04 discuss entity types and entity declara-
tions more fully, and clarify the notion of an "entity index" referred
to above.
-196-

4-02 SETS

If attributes were the only modeling feature offered, it is


doubtful whether this level would make a major contribution to model-
ing. While they provide considerable descriptive power through the
attrbute nhoe (entity nae) notation, the use of attribute values to
relate entities to one another is probably their overridl.ng contribution.
Consider the following situation: Over the ytdrs, a group of men
living in one community join various clubs and lodges. As men are
born, grow up, remain in o: move out of the community, and die, the
lodge and club memberships change. To model the relationships that
exist beteen the men of the coumunity, both over time and at particular
instants of time, we require some way of grouping the individual lodge
and club memberc together. Such a grouping is defined by the state-
ments:

EVERY COMMUNITY OWNS A MASONSAN ELKS AND A


BOY.SCOUTS
EVERY MAN MAY BELONG TO THE MASONSTHE ELKS
AND THE BOY.SC2XJTS

The first statement declares that each entity of the class COMMUNITY
awns a set called MASONS, a set called ELKS. and a set called
BOY.SCOUTS. Fach of these sets corresponds to a logical grouping
of man in the counity. This statement doas not specify which men
belong to the particular sets; rather, it establishes a system of
set pointezr and set attywibutes for the onr entities that enable
#at membereship to be constructed. Each COMMUNITY is given a logical
entity record with the following attributes automatically defined:

tSince particular SIMSCRIFT II Ispipmentationa aay store entity


data differently and there are actually two different types of en-
titias, the logical rather than physical aspects of entity-attributt
"associatiOcm are stressed.
-197-

COMM(ITY

F.MASONS
L.MASONS
F.ELKS
L.ELKS
F.BOY. SCOUTS
L. BOY. SCOUTS

The attributes etartin w-ith F. are set pointers thait point to the
first member of the respective sets. The attributes starting with L.
are set pointers that point to the last member of the respective sets.
The set ,membeos, as we shall see, point to one another, defining their
interrelationships and making the connection between the set owner and
the set members complete.
The second statement declares that each entity of the class OAN
may belong co sets called MASONS, ELKS and BOY.SCOUTS. It is impor-
tunt to note that membership is declared am possible in this statement
and not mAde mandatory. As might 1-e expected, this statement auto-
matically defines set attributes for member ent.ties:

MAN

P. MASONYS
S.MASONS

S.ELKS

P.BOY. SCOUTS
OUJT 5
S.90Y. -SC'

The attributes startinX vith P. are sot pointers pointing to tho


prvi,--veesr ,, in the indicated set; the attributes starting vith
S. are sot pointers ponting to Lho -sený'r ? in ;'ie indizated
set. The coclerts of predecessor and iuccessor, as Vei. a, '"rg, a:J,!

"last, can be best erilain-d by a.: illustrattL-n. In .rig. -- w'e


-198-

entity COMMUNITY owns one set called MASONS. The members of the set
are entittas of the class MAN. The entity-set relationships are
defined by the statements:

EVERY COMMUNITY OWNS SOME MASONS


EVERY MAN MAY BELONG TO THE MASONS

The entity records shown contain the automatically generated ownership


and membership pointers F.MASONS, L.MASONS, P.MASONS and S.MASONS.

COMMUNITY

F. MASONSMA

L. MASONS P. MASONS

Fig. 4-im -- Owner-,member set relationships

Th. set ower, the entity namd COMM4UNITY, has tw7o attribute.
Z~ogioalZz/ first and last
that point Lothe member entities that arehere called MANM1 , MAN2,
member entitie,

r1MA
in the set MASONS. The

.....
4 , have two attributas
MAN that point to the members of the
3 , and
MAN
F.MASONS in
set that logicaZty precede and succeed the.. Thus,
~MAN indicating that it is
COMMUNITY points to the entity record of MANl 1,
.4-u

The pointer P.MASONS


the first entity (logically) in the set MASONS.
value), a. MAN no predecess•:
1 hasMAN
of MANl , points nowhere (has a rerohoNwver, points to 2 which
in MASONS. The S.MASONS pointer,
2 points
MAN
in a shown, P.MASONS of
MASONS;
logically follows it
3 . MAN 4 , as
MAN
MAN. The sme is true of
back to its predecessor,
-199-

the last member of MASONS, differs somewhat. It has no successor,


and is pointed to directly by L.MASONS, the last-in-set pointer of
COMMUNITY.
The items to note from this example are:
(1) A set is made up of entities that point to one another,
thereby expressing their member relationships.
(2) First and last-in-set pointers join a set's owner and its
member entities.
(3) A specific entity can own or belong to any number of sets
so long as it has the required pointer attributes. For example, the
entity MAN might own the set CHILDREN whose members are also entities
MAN. These relationships might be defined by the statement:

EVERY MAN MA`4 BEL:AG TO THE MASONS,OWN


"SONE CHILDREN AK3 BELONG TO THE CHILDREN

Figure 4-2 illustrates a collection of MAN entities having one possible


relationship to each other.

COMMUNITY

.. MAN1 CHILDREN F. MASONS


a......*MAI1 2 CHILDREN L. MASONS

MANI MAN 2 MAN 3 AN. MAN 5 MAN6

P.MASONS 0 "
S.MASONS O 0
F.CHILDREN S0 0 0 i
L. CHILDREN 0 O /0
P. CHILDREN 0 0 /

S. CHILDREN 0

Fig. 4-2-- Set relationships


-200-

The relationships expressed in Fig. 4-2 are:

(a) COMMUNLIY owns the set MASONS wbose members are MAN 1 , MAN 3,
MAN 4 , and MAm5,
(b) MAN, ownu a set CHILDREN whose members are MAN 2 . MAN 6 - and
MAN 5.
(c) MAN 2 owns a set CHILOREN whose single member is MAN 4 .

These relationships are depicted in Fig. 4-3.

.,..... .... o........................

MANI UA-- /

MAN1 CIDD4 jMAMIS ujb


&A
A
1/

V-------
MAK CNXItDRI
2
•--
MAN
....-.....
4

Fig. 4-3 -- Set relationshipF

An entity's attributes and set relationships can be declared in


one or more EVERY statements us•,g attrbute ncre clases, set owner-
ship clauees, and set membership clTases. TE,3 -zl.uses have the form

1u o HAS attribute name list


attribute cZatss or
EAVE attribute, none list

OWNS set lam list


set ownership clause or OWN set nome list

BELONGS TO set name list


set membership clcuse or BFLONC TO oat rae list

When more than one clause is used in an EVERY statement, adjacent


clauses are separated by commas. If desired, a clause z.an he preceded
by the words MAY or CAN. Some examples &re:

EVERY MAN HAS liat,OWNS list AND MAY BELONG TO ii&,


EVERY CITY OWNS lLat AND HAS list
EVERY CAR HAS Ziot,ANO MAY OWN list
-201-

The items in an attribute name or set name list must be separated


by both a comma and one of tne words A, AN, THE or SOME. Some examples
are:

EVERY MAN HAS A NAMEAND AN ADDRESS,OWNS SOME


CHILDREN AND MAY BELONG TO THE MASONS,A CHURCH,
A FAMILY AND AN ALUMNI.CLUB
EVERY X HAS A PA Q,A Z AND AN A
EVERY PROGRAM HAS AN ENTRY,OWNS SOME LARELS,
BELONGS TO A PREAMBLE AND HAS A LENGTH

Set names follow the sa..e naming conventions as entities and


attributes and, like them, must be unique.
EVERY statements define data structures. The next several set-
tions explain how these data structures are created and used and the
items in them given further definition.

4-03 TEMfPORARY ENTITIES

An EVERY statement defines the structure of a class of entities.


Entity classes can be of two types -- temporary or permanent. This
section discusses temporary entities; Sec. 4-04 discusses permanent
entities.
When the statement

TEMPORARY ENTITIES

appears before a collection of EVERY statements in a preamble, it


declares that all following entities are temporary. This means that
storage is allocated to entities individually as they are created
during the course of program execution. Individual entity records
are provided for each temporary entity when a CREATE statement is
encountered. This statement is of the form
CREATE entity ncwne CALLED ,aia-blc

When executed, a CREATE statement finds a contiguous number of words


in memory for the attributes and set pointers of the entity class
designated, and assigns a pointer to these words to the Indicated
variable. Each entity so created is a unique and distinc7 individual
that is identified by its pointer word. From here on, we shall refer
-202-

to this pointer word as the identification number of the eatity. As


long as variables into which identification numbers are placed are
distinct, the identity of individual entities is preserved. For example:

Entity definition in a preamble:

TEMPORARY ENTITIES
EVERY SHIP HAS A NAME AND A TONNAGE
CREATE statements in a program:

CREATE SHIP CALLED VESSEL


LREAfE SHIP CALLED V(I)

These two CREATE statements assign different entity records to the


variables VESSEL and V(I). VESSEL points to a block of words in core,
while V(I) points to a different block of words.

NAME

VESSEL TONNAGE

NAME

TONNAGE

If desired, the words A or AN can be used after CREATE to improve


readability, as in
CREATE A SHIP CALLED QUEEN.MARY
CREATE AN EVENT CALLED BIRTH
If no variable is specified in a CALLED clause, the entity identifica-
tion number is assigned to a global variable vith the same name as the
entity class, e.g., the statement CREATE A SHIP finds two available
consecutive vords in memory and puts a pointer to then in a global
variable namd SHIP that the system automatically provides. The
-203-

convention that assigns a global variable to each entity class, e.g.,


SHIP to SHIP, will be usefully employed in later sections. The global
declaration is done automatically by the SIHSCRIPT II system - just
as though the programmer had written the statement

DEFINE entity now AS AN INTEGER VARIABLE


To refer to the attributes of a temporary entity, one uses the
form attribute (identification "umber) as in NAIE(VESSEL) and TONNAGE
(QUEEN.MARY). Since attributes are words in memory, like variables,
they can be used the same way variables are used, in input/output,
decision, and computation statements. the following program illus-
trates this:

PREAMBLE
NORMALLY.MODE IS INTEGER
TEMPORARY ENT!TIES
EVERY SHIP HAS AN AGE AND A TONNAGE
DEFINE V AS 1-DIMENSIONAL ARRAY
END

MAIN
READ N RESERVE V AS N
FOR I- TO NDO
CREATE A SHIP (ALLED V(I)
READ AGE(V(I)) AND TONNAGE (V(I))
LOOP
'READ' READ OLD
FOR I-1 TO N,WITH AGE(V(I)) < OLD,
ADD TONNAGE(V(I)) TO SUM.TON$
PRINT 1 LINE WITH OLD,SUM.TONS THUS
TOTAL TONNAGE OF SHIPS LESS THAN ** YEARS OLDu******
LET SUM.TONS-O
IF DATA IS ENDEDSTOP
ELSE GO TO READ
END
In this program N temporary entities of the class SHIP are
created and their identification numbers stored in the subscripted
variables V(1),V(2)....,V(N). The attributes of these entities are
accessed in READ, WITH. and ADD statements.
As temporary entities are created, entity records are fetched
from a pool of unused memory vords. The assignment of entity records
to entities is similar to the assignment of pointer and data words
to
-204-

arrays as they are reserved. Like arrays, entities can be released


when they are ne : needed. To do this, the statement

DESTROY entity name CALLED variable

uses the identification number of the entity stored in the indicated


variable to point to a block of memory words that are to be released.
When destroyed (released), the words are returned to the pool of un-
used memory words for later use. The words THE or THIS can be used
before the entity name, if desired, as in:

DESTROY THE SHIP CALLED VESSEL and


DESTROY THIS SHIP CALLED V(I)

A short form of this statement using only an entity name

DESTROY entity name

is treated as
DESTROY entity name CALLED entity name

The statement
DESTROY THE SHIP
is interpreted as

DESTROY THL SHIP CALLED SHIP

4-04 PERMANENT ENTITIES

Permanent entities are defined in a similar manner as temporary


entities, by preceuilng the EVERY statements declaring them by the
statement

PERMANENT ENTITIES

Entities declared as permanent are stored collectively rather than in


individually identifiable records. A group of permanent entities ts
created by a jingle statement; the attrlbutis of the entities in the
group are stored as indexable arrays. The number of entities in a
group is specified by a variable N.ent>-tu. Attribute arrays are
allocated by a CREATE statement of a different form from that used
for temporary entities. Given the preamble declaration
-205-

PERMANENT ENTITIES
EVERY HOME HAS AN ADDRESS AND AN AREA

and the assignment of a value to N.;;OME by a READ or LET statement,


the statement

CREATE EACH HOME


allocates arrays for the attributes of the N.HOME untities of the
class HOME by executing the statement RESERVE ADDRESS AND AREA AS
N.HOME. That is, the attributes of permanent entities are stored in
arrays and are reserved together when a CREATE statement is encountered.
In such statements, the words EVERY and ALL can be used in plate of
EACH. Several permanent entities can be created together by naming
a list of entity names, as in

CREATE EVERY HOME,HOTEL AND RESTAURANT

which is of the general form

CREATE permanent entity nane liat


If the value of N.entity has not been specified, an arithmetic
expression can be used in the CREATE statement to indicate the size
of the attribute arrays. For example, the following statements are
equivalent:

(1) LET N.HOME = 5


CREATE EVERY HOME
(2) CREATE EVERY HOME(5)

When the second form is used, N.entity is set to the value of the
parenthesized expression.
Entities so created are referred to, not by an identification
number that is a computer location, but by an index. Thus we speak
of ..S attributes of each HOME as ADDRESS(1),ADDRESS(2),...,ADDRESS(5),
AREA(1),AREA(2),...,AREA(5). The layout of these attributes is shovn
in Fig. 4-4.

I
- -~--
-206-

ADDRESS AREA

2 2
3 _ 3
44

Fig. 4-4 -- Attribute storage of


permanent entities

The program of Sec. 4-03 is repeated here, using permanent rather


than temporary entities to illustrate the difference in how they are
defined and used.

PREAMBLE
NORMALLYMODE IS INTEGER
PERMANENT ENTITIES
EVERY SHIP HAS AN AGE AND A TONNAGE
END

MAIN
READ N.SHIP CREATE EVERY SHIP
FOR 1-1 TO N.SHIP,
READ AGE(I)oTONNAGE(I)
'READ'READ OLD
FOR I1- TO N.SHIP WITH AGE(I) < OLD.
ADD TONNAGE(I) TO SUM.TONS
PRINT 1 LINE WITH OLDSUM.TONS THUS
TOTAL TONNAGE OF SHIPS LESS THAN * YEARS OLD-*****
LET SUK.TONS-O
IF DATA IS ENDEDlSTOP
ELSE GO TO READ
END

Unlike temporary entities, permanent entities c4nnot be destroyed


individually; they can be destroyed collectively by releasing all
their attributes in RELEASE statements. as in

RELEASE AGE AND TONNAGE

All attributes of permanent entities mast be released at the see time.


Like temporary entities, permanent entities have global variables
defined for them. Each statement of the form

EVERY enti.t,
-207-

prompts the atitomatic generation of a statement

DEFINE entity now AS AN INTEGER VARIABLE

4-05 SYSTEM ATTR"BI]TES

For reasons that will become clear in succeeding sections, it is


often desirable to use system attributes rather than global variables,
The statement

THE SYSTEM HAS attribute nze tiat

declares that the listed names are attributes of the program as a


whole - what we call the "system." For most purposes the statements

(a) THE SYSTEM HAS AN X AND A Y and


(b) DEFINE X AND Y AS VARIABLES

are equivaleut. Since there is only one system, references to system


attribiutes need not be indexed, as do references to attributes of
permanent and temporary entities. A value of 1 is assigned to the
variable X by the statement LET X-1, whether X is defined by (a) or
(b) above. System attributes will be subscripted if the background
dimensionality condition at the time of their declaration is greater
than zero. X is declared to be r 2-dimensional system attribute by
the statements

NORMALLY, DIMENSION IS 2
THE SYSTEM HAS AN X

The importance of system attributes lies not so much in their


use as global variables, but as pointers that enable a program as a
whole to own sets. The statement

THE SYSTEM OWNS A QUEUE

specifies that a program contains two INTEGER system attributes named


F.QUEUE and L.QUEUE that point to the first and last entities belong-
ing to a set named QUEUE, Several systep-owned sets can be defined
at one time by the statement

THF SYSTEM OWNS so: irw Zs


-208-

The following preamble illustrates some typical set declarations.

PREAMBLE
NORMALLY.MODE IS INTEGER
THE SYSTEM OWNS A SCHOOL
PERMANENT ENTITIES
EVERY STREET HAS A SIGN AND OWNS HOUSES
EVERY HOUSE HAS A NUMBER, OWNS A FAMILY AND
BELONGS TO SOME HOUSES
TEMPORARY ENTITIES
EVERY PERSON HAS A NAMEAN AGEA SEX.BELONGS
TO A FAMILY AND MAY BELONG TO A SCHOOL
EVERY FAMILY OWNS SOM.E PERSON
END
Subscripted system-owned sets are defined by setting a dimensionality
background condition that makes the set pointers arrays, rather than
unsubscripted variables, a in

NORMALLY. DIMENSION - 2
THE SYSTEM OWNS A TABLE AND HAS A MATRIX

Subscripted system attributes used as data or as act pointers must 6e


RESERVED before they can be ised. To use the system set TABLE and
the syptem array MATRIX, a statement such as
RESERVE F.TABLE,L.TABLE AND MATRIX EACH N BY M

must be executed.

4-06 AZTR:BUTE DEFINI'TIONS--WPE A.VN: ?A•AVS.' AL1T"

Attributes of the system, and of vermanent and temporary entities,


-an be INTEGER, REAL, or ALPrA value(!. As with global and local va-t-
ables, modes can be declared by defailt, using NORMALLY statements,
and expikcttly, -,inig DEF!N.E statements. Excest for set pointers,
whtich are autoestically define- as INTEGER, all attributes are sus-
ceptible to p-ograwr definition.
?armanent and temporary entity declarations define the limen-
sionality of their attributes impiicitlv. mAking additional' defini-
tions unnecessary. The atatent

EVERY K0 HAS AN AGE

declares that AGE t-as a sinale su•scrtpt, an identification n;,.ber if


-239-

MAN is temporary, or an i:.dex if MAN is permanent. The notation AGE(I).


read AGE of I. provides for this subscript.
System attributes, on the other hand, must be declared and re-
served as explained in Sec. 4-05.
The rules for assigning modes and dimensiousalities to attributes
are straightforward:

(a) The current "background mode" is assigned


to all attributes specified in EVERY and
THE FVSTEM statements except for auto-
matically generated set pointers that are
always INTEGER.
(b) DEFINE statements foZZowng EVERY and THE
SYSTEM statements can redefine attribute
modes.

(a) The current "background dimenaionality"


is assigned to all attributes and sets
Dimensiona•ity specified in THF SYSTEM statements.
(b) EVERY statements specify the dimensionality
of the attributes and sets listed in them.

The following preamble illustrates each of these rules:

PREAMBLE
NORMALLY DIMFNSION IS 2
THE SYSTEM HAS AN EXCESS
DEFINE EXCESS AS AN INTEGE1 ARRAY
NORMALLY DIMENSION - 0,
MODE IS REAL
THE SYSTEM HAS A VALUE AND
OW14S A COLLECTION
PERMANENT ENTITIES
EVERY SAMPLE BELONGS TO T1Er COLLECTION
AND HAS A PRICE ANC A SAME
TEWPORARY ENTITIES
EVERY POINT HAS AN IDENTITY AND A
TIME.OF.COLLECTION
DEFINE NAME AND ID[NTITY AS ALPHA VARIABLES
END

"'h.i reaske defines tour eyeten attribtes., one of w1hich is REAL


valued ,V{, one uf which is a ba, Tpwintor for a tvo-4inaina1
array (EXC-SS) who.. el ments ar. INTEGER vauec, anad tvo o'f wh!ch are
INTEGER-valued sat pointers (F.COLLECTIOh,L.CO4LLCTI7OW,. It a~so
-210-

defines a class of permanent entities (SAMPLE) and a class of temporary


entities (POINT). Each entity of type SAMPLE has two INTEGER attrib-
utes (P.CCLLECTION and S.COLLECTION), a REAL attribute (PRICE), and
an ALPHA attribute (NAME). These attributes are stored as one-dimien-
b~onal arrays of dimension N.SAMPLE. Each entity of type POINT has
an ALPHA attribute (IDENTITY) and a REAL attribute (TIME.OF.COLLECTION).
These attributes are stored in individual words of temporary entity
records. Figure 4-5 illustrates the storage of the attributes of
N.SAMPLE permanent entities of the class SAMPLE.

SAMPLE
base pointers 1 2 . N. SAMPLE

P. COLLECTION -"

.N. SOLECTIO

NAME

Fig. 4-5 -- Storage of attributes of a permanent entity

Figure 4-6 illustrates the layout of an entity record for a


temporary entity of the class POINT.

IDENTITY

TIME. OF. COLLECTION

Fig. 4-6 -- Storage of attributes


of a temporary entity

Figure 4-7 illustrates the arrangement in memory of the system


attributes VI,LUE. EXCESS, F.COLLECTION. and L.COLLECTION.
-211-

INTEGER data values

VALUEE
Row pointers
EXCESS (base pointer)

F. COLLECTION

L.COLLECTION L iI ]L

Fig. 4-7 -- Storage of system attributes and set pointers

4-07 ATTRIBUTE DEFINITIONS--PACKING AND EQUIVALENCE

Thus far, all discussions of data have assumed that data values

are stored individually in separate and distinct computer words.


While this is by far the most usual form of data storage, situations

exist whereby more than one data value must be placed in a single
computer word. The vost commonly encountered reason for doing this
is to "squeeze" programs with large data requirements into limited
memory space.
When more than one data value is placed in a computer word, the

values are said to be packed in the word. When a data value is given
different names the names are said to be equivalent. SIK'CRIPT II

offers facilities for packing INTEGER and ALPHA and equivalencing


INTEGER, ALPHA, and REAL attribute values. Subscripted system attrib-
utes, and attributes of temporary and permanent entities, can be

packed and equivalenced. Unsubscripted system attributes can only


be equivalenced. This is one reason for defining certain values as
system attributes, rather than as global variables, which can be
neither packed nor equivalenced.

Attribute packing is specified by attaching a pack-'ng factor

enclosed in parentheses to an attribute name. Three types of packing


-212-

are avPiiable: field, bit, and intra. Field and bit packing apply
to all subscripted attributes; intrapacking applies only to sub3cripted
system attributes and to attributes of permanent entities.
The SIMSCRIPT II system uses programmer-specified packing factors
t, store and retrieve data values. The fact that data are packed is
reflected in a program's preamble but not in its executable state-
ments. A programmer operates at all times on a logical level., e.g.,
AGE(MAN); the SIMSCRIPT II system determines where AGE(MAN) is phys-
ically located.
Using field and bit packing, data fields can be laid out within
computer words. The field packing notation (1/2) specifies that the
attribute value to which it is attached is to be put in the first
half of a computer word. The bit packing notation (1-16) specifies
that bits 1 through 16 are to be used to store an attribute value.
Since computers differ in word size and in instructions available to
access parts of words, it is impossible to specify all the possible
field and bit packing factors available in different SIMSCRIPT II
implementations. Table 4-1 shows the packing factors available in
an IBM 360 implementation; readers using other implementations will
have to consult their implementation manuals for the packing factors
av&ilable to them.
Attrl'ute names are processed as they appear in EVERY statements,
and are assigned their indicated positions within successive computer
words. Attribute equivalence is specified bv placing parentheses
around a list of attributes. All attributes within parentheses are
assigned to the same computer word; if two attributes have the same
packing factors, their names are synonyms. Overlapping packing fac-
tors can be specified. Attributes enclosed in equivalencing parenthe-
ses appear in a list, without the words A, AN, or THE before them.
The parenthesized list must, however, be preceded by one of these
words. The following examples illustrate the use of field and bit
packing fa-tors for attributes of temporary entities:

tOr bytes, or digits, depending on the computer implementation.


-213-

Table 4-1

FIELD AND BIT PACKING FACTORS FOR IBM 360

Field Packing Factor Attribute Value Placement

1/2 first half of computer wPrd


2/2 second half of computer word
1/4 first quarter of computer word
2/4 second quarter of computer word
3/4 third quarter of computer word
4/4 fourth quarter of computer word

Bit Packing Factor Attribute Value Placement

n - m bits n through m inclusive


1 < n < 32
1 < a < 32
n < m

TEMPORARY ENTITIES

(a) Declaration:

EVERY MAN HAS AN AGE AND A NAME

Entity record:

word I AGE

wvrd 2

(b) Declaration;

EVERY MAN HAS AN (AGE(1/2) AND NAME(2/2'))

Fntitv record:

word I LAGE SAE<


-214-

(c) Declaration;

EVERY MAN HAS AN AGE(1/4), A NAME AND A SEX(1/4)


Entity record: word I

word 2 NAME
word 3 SEX

(d) Declaration:

EVERY MAN HAS AN (AGE(O-8) AND NAME(9-32))

Entity record: 1 9 32
word 1 AGE INAME I

(e) Declaration:

EVERY PART HAS A (RIGHT.VALUE(2/2),LEFT.VALUE(1/2),TOTAL.VALUE)

Entity record: TOTAL.VALUE

wvord 1 ILEFi .VALUE RIGHT.VALUEJ


(f) Declaration:

EVERY MAN HAS AN (AGE(1/4),NAME(2/4),WEIGhT(17-32))


AND OWNS A FAMILY

Entity record:
word 1 AGE A WGHT

word 2 F.FAMiLY
vord 3 L.FAMILY

(g) Declaration:

EVERY MAN HAS AN AGE(1/4),OWNS A FAMILYHAS A (NAME(2/4)


AND WEIGHT(2/2))
Entity record:
word 1 AGE
word 2 F.FAMILY
word 3 L.FAMILY
word j NAM 4EI T
-215-

Field and bit packing of attributes of permanent entities and


subscripted system attributes places two or more attributes in the
sam array. The declaration

PERMANENT ENTITIES
EVERY HOUSE HAS AN (ADDRESS(1/2).AND ZIP(?/2))

placea similarly indexed values of ADDRESS arl ZIP in the same com-
puter word. This declaration, followed by the statement CREATE EVERY
HOUSE (5) allocates storage as follows:

N ADDRESS(1) ZIP(1) word I


ADORESS(2) ZIP(2) word 2
Base Pointer of ADORESS(3) ZIP(3) word 3
ADDRESS and ZIP ADDRESS(4) ZIP(4) word 4
ADDRESS(S) ZIP(S) word 5
More than one set of attributes, of course, may be packed in a
single EVERY statement, e.g.,

EVERY SHIP HAS A (TONNAGE(1/2),A CAPACITY(2/2)),A


(DESTINATION(1/2) AND HOME.PORT(2/2))

This rtatent pairs the attributes TONNAGE and CAPACITY and the
attributes DESTINATION and HOWE.PORT in adjacent parts of attribute
arrays. Some additional *xamples follow.

PERMANENT ENTITIES

(a) Declaration:

EVERY HORSE HAS A NAME AND AN OWNER

Attribute arrays:

No~ word 1 LýEý


word 2

word N.HORSE

NW and OWNER are separate arrays.


-216-

(b) Declaration:

EVERY HORSE HAS A (NAME,OWNER)

Attribute arrays: NAME

word 1
word 2

word N.HORSE

NAME and OWNER refer to the same data array.

(c) Declaration:

EVERY HORSE HAS A (NAME(1/2),OWNER(2/2))

Att:ibute arrays:

word 1
word 2

word N.HORSE

NAME ig stored in the left half, and OWNER in the right half of
a data array.

SYSTEM ATTRLIUTES

(a) Declaration:

NOPALLY, DIMENSION - 0
THE SYSTEM HAS A HIGH AND A LOW

Attribute&:
HI GH LOIW.
-217-

(b) Declaration:

NORMALLY, DIMENSION 1
THE SYSTEM HAS A HIGH AND A LOW

Attributes:

word 11
word2 2

0 .

wordNNM

(c) Declaration:

NORMALLY, DIMENSION - I
THE SYSTEM HAS A (HIGHLOW)

Attributes: HIGH

LOW
word 1
word 2

word N

HIGH and LOW are synonym#.


-218-

(d) Declaration:

NORMALLY, DIMENSION 1
I
THE SYSTEM HAS A (HIGH(1/4), LCO(2/2))

Attributes: WYiGH7

LLordOW
word 1
word 21

word N _

The second quarter of each data word is unused.

Intrp'aking is used to compress array storage of subscripted


systm attributes and attributes of permanent entitles. The intra-
packing notation (*12) specifies that two values are to be packed in
one word, i.e., the array in which they are stored is compressed.
For example, the declarations

NORMALLY, DIMENSION - 1
THE SYSTEM HAS A LIST(*/2)

and the ststimnt RESERVE LIST(*) AS 10 saecifies and allocates storage


to LIST as followm:

word I LIST(1) LIST(2)


base pointer of LIST word 2 LIST(3• LIST(4)
word 3 LIST(S) LIST(6) J
word 4 LIST(7) LIST(8)
word 5 LIST(9) LIST(10)

When a system attribute is sltidimnsional. pecking takes place


at the data-storage level only; the array pointer words arc unpacked.
Thus the statements
-219-

NORMALLY. DIMENSION * 2
THE SYSTEM HAS A LIST(*/2) and
RESERVE LIST(*,*) AS 3 BY 4

Apecify %.nd allocate storage to LIST as follows:


E--•~ LST(,1) ýLIST(ý1.2 ýLLS T(I,3 '-i L"Z'l_STi

Base Pointer _ý•3:LIST(2,2)I LIST(ý23) - ýLISTý2,4')


ofLIST[ LIST(3.1) : LIST(3,2)[ LIST(3,3) ,LIST( 4)

Row Pointers Attribute Values

As with field and bit packing, intrapacking specifications depend


ou comp•:er implementation. Table 4-2 shovy permissible intrapackiri
factors for the IBM 360; other implementations have their permissible
factors specified in their implementation manuals.

Table 4-2

INTRAPACKING FACTORS FOR IBM 360


Intrapackin$ Fictor Attribute Valw_ Placement
(*/2) 2 values per word
(*/4) 4 values per word

When necessary, further a-ecificaticm can be made of attribute


values to entity arrays or records. Attributes of temporary entities
can be assigned to particular words of entity records by following
their declaration by the clause IN WORD i, vhere i is an integer con-
stant, as in examples (a) and (b) below:

(a) Declaration:

EVERY IMAN OWNS A FAP4ILY.HAS AA AGE IN WORD 1. AND HAS A NAME

Entity record:

word I AGE
vord 2 F.FAMILY
word 3 L.FAMILY
vord 4 NAM
-220-

(b) Declaration:

EVERY MAN HAS AN (AGE(1/4),SEX(2/4),NAME(2/2))


IN WORD I AND A DEBT IN WORD 2
Entity record:

word 1 AGEiSXT NAME

word 2 DEBT

Specification of the word tn a temporary entity record in which


an attribute value is located is required for common attilbbutea,
attributes that are common Lo more than one entity class. All common
attribute values must be in the same resa "e locations in all entity
records, and hence mist have the same packing factors and word assign-
ments whenever they appear. For example:

EVERY MAN HAS AN (AGE(1/2).NAME(2/2)) IN


WORD 1.OWNS A FAMILY AND BELONGS TO
A LODGE
EVERY WOMAN HAS AN(AGE(1I/2.NUAME(2/2)) IN
WORD 1,AND BELONGS TO A AMILY
Since AGE and NAME are common to both MAN and WOMN, they have the
smme packing factors and word specification in' both EVERY statements.
When entitiom belong to commcm sets their set pointere must be
explicitly declared and located. In the above example, if both en-
tities of the class MAN and WOAN belonged to the set FAMILY, the
declarations vould have to be rewritten as:

EVERY MAN HAS AN(AGE(1/2),NAME(2/2)) IN


WORD 1,OWNS A FAMILY.BELONGS TO A FAMILY
AND HAS A P.FAMILY iN WORD 4 AND A S.FAMILY
IN WORD 5
EVERY WOMAN HAS AN(AGE(1/2),NMW(2/2)) IN
WORD 1.BELOS.S TO A FAMILY AND HAS A
P.FAMILY IN WORD 4 AND AN S.FAMILY IN WORD 5

Entity reeor4s of MU and vould look like:


w
-221-

MAN WOMAN
word 1 AGE INAME AGE NAME
word 2 F. FAMILY unuaed
word 3 L.FAMILY unused
word 4 P.FAMILY P.FAMILY
word 5 S.FAMILY S.FAMILY

Putting the set pointers O.FAMILY and S.FAMILY in words 2 iand


3 in this example, rather than in 4 and 5, would save two words in
each WOMAN record.
Care must be taken when mentioning set pointers in EVERY statements
that they are not i-Advertently defined as something other than INTEGER.
Moreover, every qualified set pointer mtat be listed in any EVERY statement.
Attributes of permanent entities and system attributes are not
"asigned to words but to arrays by the clause IN ARRAY i, where i is
an integer constant. This is important in certain implementation5,
as it affects the compilation process; specifying an attribute's
array number can often lead to compiler efficiencits.
The results of packing, equivalence, and word and array specifi-
cation are shown in Table 4-3.

Table 4-3

ATTRIBUTE SPECIFICATIONS

Specification Assignment

No packing, equivalence, or Attributes assigned to separate


word or array specification words or arrays in the order of
their appearance In preamble
Word or array specification Attributes are assigned to
specified vords or arrays;
remaining attributes assigned
as above
Equivalence specification Specified attributes assigned
to the same wrd or array
Packing specification Field and bit pock!n" used to
place more then --
me attribute
within a computer vord
Intrapacking used •o compress
storage for arrays
-222-

The EVERY statement thils rermits a great deal of specification,


or lack of specification, of an entity's attributes. The use of
packing facto:s, equivalence parentheses, and WORD and ARRAY clauses
gives a programmer a good deal of control over the allocation of com-
puter storage. Succeeding sections elaborate on entity-attribute-set
definitions, introduce statements for using entities, attributes, and
sets, and present programing examples.

4-08 AI1RIBUTE DEFINITIONS--FUNCTIONS

When defined by statements of the form

THE SYSTEM HAS AN attribute nne• FUNCTION


EVERY entit now HAS AN attribute now FUNCTION

a system attribute or an attribute of a permanent or temporary entity


is treated as a function and not as a variable. That is, a subprogram
having the same name as the declared attribute must be provided. The
subprogram must have the same .•umber of arguments as the declared or
implied dimensionality of the attribute, i.e., no grguments for an
unsubscrtpted system attribute, one argument for an temporary or per-
manent entity, two arguments for a 2-dimensional system attribute, etc.
Function attributes, because they are computational procedures,
have no storage space allocated to them. Declarations of attributes
as functions interspersed between other attribute declarations have
no effect, therefore, on storage allocation of attributes to arrays
or entity records. The following example illustrates this:

Declaration:

EVERY AUTO HAS A(PASSENGER.LIMIT(1/2),AND


WEIGHT(2/2)),A FUEL FUNCTION,A CONSUMPTION.RATE,OWNS SOME PASSENGERS
AND HAS A FUEL.CAPACITY AND A DEPARTURE.TIME
Entity record:

word I PASSENGER.LIMIT WEIGHT


word 2 CONSUMPTION.RATE
word 3 F.PASSENGERS
word 4 L.PASSENGERS
word 5 FUEL.CAPACITY
word 6 DEPARTURE.TIME
-223-

Assume the attribute function FUEL is defined by the following


program:

ROUTINE FOR FUEL(AUTO)


RETURN WITH FUEL.CAPACITY(AUTO)-(TIME-DEPARTURE.TIME(AUTO))*
CONSUMPTION.RATE(AUTO)
END

The amount of fuel currently in a particular auto, assuming that


the current time is contained in the global variable TIME, can thus
be found by writing LET AMOUNT=FUEL(AUTO). As the variable TIME
changes, the reported value of FUEL changes.
Function attributes have a number of uses: they can be used, as
above, to determine values of continuously changing quantities; to
t
perform complex calculations; to define optional attributes; and
to perform monitoring, printing, and other input/output operations.
An example follows:

Declaration:

EVERY MAN HAS A CREDIT.RATING FUNCTION,A BANK.BALANCE,


A DEBT.TOTAL,A MORTGAGE.PAYMENT,A NUMBER.OF.DEPENDENTS
AND A SALARY

Function attribute definition:

ROUTINE FOR CREDIT.RATING(J)


IF (SALARY(J)-MORTGAGE.PAYMENT(J)) < 00" NUMBER.OF.DEPENDENTS(J)
OR DEBT.TOTAL(J) > 4*BANK.BALANCE(J),RETURN WITH 0
OTHERWISE RETURN WITH 1
END

Program statement:

I IF CREDIT.RATING(CUSTOMER)=O,GO
ELSE CALL ACCEPT.CREDIT
REFUSE.CREDIT

4-09 MORE ON SETS: THEIR DECLARATION AND USE

Sets, as we have described them, are collections of entities


organized by systems of pointers. Set owners point to the first and
last members of sets; set members point to one another. Sets are

SSee Sec. 4-14-6.

f
tI'
-224-

like arrays in that they are composed of elements that can be identi-
fied and manipulated, but are unlike arrays in their method of organi-
zation and their dynamic and changeable, rather than static and fixed,
nature.
As described in previous sections, sets are declared in EVERY
statements when their owner and member antities are defined. Every
set must have an owner, either an entity or the system, and can have
either permanent or temporary entities as members. When more than
one type of temporary entity belongs to a set, the predecessor and
successor attributes of the entities must be located in the same
words in the entity records.
Sets named in EVERY statements have the following properties:

(a) Owner entities have first and last pointers named F.set
and L.set;
(b) Member entities have predecessor and successor pointers
named P.set and S.set;
(c) Set members are ranked on a first-in, first-out basis when
they are put in a set. This ranking gives the highest
priority to the first entity put in a set;
(d) A request to remove an unspecified entity from a set removes
the entity with the highest current priority;
(e) Each member entity has a memberohip attribute named M.set
that is "yes" if an entity is in the set and "no" if it is not;
(f) Each owner entity has a counter attribute names N.set whose
value is the number of member entities currently in the set.

All set owner and member attributes are INTEGER valued and have names
t
formed by prefixing a letter and a period to the set name.

The declarations

PERMANENT ENTITIES
EVERY CITY OWNS A CLUB
TEMPORARY ENTITIES
EVERY MAN MAY BELONG TO THE CLUB

define three attributes for the owner entity of CLUB and three attri-
butes for its member entities. Since CITY is a permanent entity, its
owner attributes are stored as arrays:

tWhile normally INTEGER, N.set and M.set attributes can, when


necessary, be defined as REAL.
-225-

vord 1
word 2

word N.CITY

MAN, being a temporary entity, has Its member attributes stored in


individual entity records:

MAN
word I P.CLUB
word 2 S.CLUB
word 3 M.CLUB

Every program commences execution with empty sets. As a program


proceeds, statements are executed that file entities in sets, examine
sets, and remove entities from sets. Set memberships change dynamic-
ally when FILE and REMOVE statements alter set pointers, changing
relationships that affect set membership and s,'t ranking. The FILE
statement has two basic forms:

ka1 ) FILE wiOknti. expression FIRST IN set


(a2 ) FILE arithmetic expreseion LAST IN set
(b 1 ) FILE arith-wtio expression BEFORE ar-tpvwtic expression IN set
(b 2 ) FILE ayrithmetic expression AFTER arithmetio expression IN set

The words FIPC•T or LAST are optional. When both are omitted, FILE
LAST is implied; the statements
FILE arithmetic #xpv*.;cn. LAST IN set and
FILE mr-ithmtio exprission IN Pet

are equivalent.
In each of the forus, the words THE or THIS are optional before
the expression or the set name, as in
-226-

FILE THE BIRD IN THE NEST


FILE THIS JOB FIRST IN THIS QUEUE
FILE FIDO AFTER ROVER IN THE KENNEL

Used in this context, an arithmetic expression must evaluate to an


entity identification number; it must be either the address of a
temporary entity record obtained from a previous CREATE statement or
an integer number denoting one af N.entit, permanent entities of a
specific type.
In case (a), the indicated item is filed at the head (tail) of
the set, and It is given top (bottom) priority. In (b), the position
of filing is specified. The actions that take place when a "FILE
FIRST" statement is executed are illustrated by two examples. The
examples use a set whose owner and member entities are both temporary,
but they can as vwll be both permanent, or one permanent and one tem-
porary. The set and the entities are defined by the statementst

TEMPORARY ENTITIES
EVERY FAR4 OWNS A KENNEL
EVERY DOG HAS A NAME AND BELONGS TO SOME KENNEL
DE&INE NAME AS AN ALPHA VARIABLE
The two illustrations are included in the program segment shown below.
We first consider the situation before and after the first dog is
filed in a kannel; later we examine a subsequent situation. Assume
a FARM has been created whose identification number is stored in the
global variable FARM. This could have been done by the statement
CREATE A FARM.
Program Segment

READ NLUER.OF.DOGS
FOR 1-1 TO NUMBER.OF.DOGS.DO
CREATE A DOG
READ NAW (DOG)
FILE DOG FIRST IN KENNEL(FARM)
LOOP
The entity record of FARM looks like:
FARM
word 1 F.KENNEL
word 2 L.KENNEL
word 3 N.KENNEL
-227-

After the first dog is created, its entity record looks like:

DOG
NAME
P.ENNEL

SKENNEL

At this point th- variables F.KENNEL, L.KENNEL, N.KENNEL, P.KENNEL,


S.KENNEL and M.KENNEL are all zero, indicating that KENNEL(FARM) is
empty and DOG is not in sow KENNEL. We vill assume that M.KENNEL
is either 0 (no) or 1 (yes).
After the FILE statement is executed, the entity records look like:
FARI •DOG
F. NNEL NAM OV-- R
L
N. KENNEL
KENNEL P.ENNEL
$. ENNEL 0
MNENNEL [

The ovner entity FARM points to the uemer entity DOG: DOG, being
the only entity in KENNEL(FAR4). is both first and last. Since DOG
is alone in KENNEL(FARM) it has no predecessor or successor entities.
After the second DOG is crasted and tiled, the entity records
look like:

FARIM
F.KENNEL 0 NAME RO-VER •
L:EN E P.AENNEL • -
N.KENNELL.KENNEL NNL
S .KENNEL 0

P.KENNEL I•/
IDO
NAMFE FIDe
P.KENNEL
M. ENNEL I

With tvo members in the set, the first and last pointers lead to dif-
ferent entity records. The first entity, poi,:t.~: to rY F.KENNEL(FAR4),
-228-

pointe ahead to the second entity with its successor pointer. The
second entity pointa back at the first entity with its predecessor
pointer. Both the predecessor pointer of the f,&rst entity and the
successor pointer of the last entity are zero, indicating their re-
spective roles.
An important point to note is that the global variable DOG now
points to the second DOG (the second DOG created, not necessarily the
second in the set). The entity record of the first DOG created can
only be accessed through the pointers to it. L.KENNEL(FARM) and
S.KENNEL(DOG). These pointers illustrate the general form of an
attribute reference.

attribute (entity identification)


S..nce an entity identification can itself be an attribute, as in the
case of a pointer, nested entity references can be wmde, as in

S.KENNEL(F.KENNEL(FARM) )1'

vhich has the same v" e as S.KENNEL(DOG) since F.KENNEL(FARII)=DOG.


Any level of entity nesting is possible as long as all nested expres-
sions evaluate to entity identification numbers.
When a third DOG is created aind filed, the entity records look
like:
FARM
F.KENNEL NAME ROVER
L.KENNEL P.KENNEL
N.KENNEL S.KENNEL
M..KiNNEL ) f
P.
S. KENN E
KENNEL _ I
NAMIE E

S.KE 4NEL
P.KENNEL
KEINEL
S.
M.KENNEL -1

Additional creations and filings are analogous.

tThis is read a" "the successor of the first in KENNEL of FAR4."


-229-

A "FILE LAST" statement has an effect similar to a "FILE FIRST",


but operates on the opposite end of a set. If our example program
segment vere vritten vith the statement FILE DOG LAST IN KENNEL(FARM),
after executinS three creates and files the entity records vould look
like:
FARM .• V•",,

F.KENNEL eER N
L. KENNEL 3.N
N.KENNEL

NAME FIDO
P. KENNEL
S.KENt4EL
M.KENNEL 1

NAME REX
P.KENN EL
S.KENNEL 0
M.KENNEL I

The "FILE BEFORE" and "FILE AFTER" statements are described


through a different example.
Assume the entity record organization shown in Fig. 4-8 vas
created by the following Drogram staLements:
CREATE A DOG CALLED ROVER
FILE ROVER FIRST IN !ENNEL(FAI4)
CREATE A DOG CALLED FIDO
FILE FIDO FIRST IN KENNEL(FARM)

The statements

CREATE A DOG
FILE THE DOG AFTER FIDO IN KENNEL(FARM)

insert the entity record for the newly created DOG after the entity
record pointed to by the variable FIDO. The resultinS entity record
organization in shown in Fig. 4-9.
-230-

F.KENNEL NM
I *KENNEL PKNE
N. KENNELE

NAME
P. KENNEL 0
S. KENNEL
M.KENNELI

Fig. 4-8 -A set with two imevtbers

F.KENNEL NM
1. KENNEL PKNI
N. KENNELL

Fig.A se
-9 wit
- threm Ier

£ottt~ arer~y~dfrom ets b RE eamt.N


AME a
form ~ ~ r ~
oube ~ a~wrk
~
of0v nlgui
PKFNE o i c~
evese
pith~ h. eek of * ILE*tainn.KNE
-231-

(a1) REMOVE FIRST uoriable FROM set


(a 2) REMOVE LAST a..riable FROM set
(b) REMOVE aritnwrtic extpresion FROM set

The word THE is optional after REMOVE, "s is either of the words THE
and THIS before the set nae. In addition, either of the words THIS
or ABOVE cdn be used before the expression in form (b).
A "REMOVE FIRST" or "REMOVE LAST" statement removes from a set
the entity pointed to by the first or last pointer attribute of the
set ow r. The identification nmber of the removed entity is "ssigned
to the variable in the REMOVE statement. For instance, in the situa-
tion shown in Fig. 4-9. the statement

REMOVE THE FIRST HOUND FROM KENNEL(FARM)

removes the first entity (FIDO) from KEIP4EL(FAR4), makes the second
entity first, and puts a pointer to FIDO in HOUND. The attribute
values of FIDO, which now can also be called HOUND, are unchanged
except for M.KENNEL. Although FIDO is no longer in KENNEL(FAIR), its
attribute S.KENNEL still points to DOG. In most instances, pointer
values are meaningless once in entity is removed from a set. If the
name FIDO were replaced by DOG in Fig. 4-8, this figure would show
the organization of KENNEL(FARN) after FIDO had been removed irom
1"-&. 4-9.
If an attempt is made to remove the first or last member from an

empty set. the program terminates with a message and an error halt.
A "REMOVE specific entity" statement (form (b)) extracts a par-
ticular entity from a set; the entity identification number is given
by the arithmetic expression. Referring again to Fig. 4-9, the state-
sent
REMOVE THIS DOG FROM KENNEL(FARM)

converts the set show• in that figure to the set shown in fil. '--8.
If the arithmetic expression is not an identification number of an
entity currently in the set (signaled by a "yes" in its membership
attribute), the progrma terminates with a message and an error halt.
The presence of a membership attribute in an entity paermits both
-232-

error checking (cannot file Y after X because X is not in the set;


camnot remove X because X is not in the set; cannot destroy X if it
is a member of some sets; cannot file X in a set if it is already in
it) and questioning abouat set membership. The logical exvressions

eritiuwtic axpression IS IN set and


a'itp.etic expression IS NOT IN set

can be used in IF statements and WITH clauses to take actions con-

ditional on set membership. As options, the vords THE and THIS can
precede the arithmtic expression, and the vords A, AN, THE, or SOME
the set nine. One can write

IF ROVER IS NOT IN SOME KENNEL, or


WITH TH!S DOG IN A KEM'NE

et cetera. In these statements the set nane KENNEL cannot be sub-


scripted. It is impossible for an entity to belong to more than one
set of a given class at a time. A DOG can belong to KENNEL(FARM) or
KENNEL(HOIJSE). etc., but not to both. A membership attribute signals
class, and not specific owner, membership.
Each set's first pointer is used to determine whether or not A

specific set has members. The logical expressions

*at IS EMPTY and


set IS NOT EMPTY

are available. As vith the preceding expressions, the words THE and
THIS are alloyed before the set name to improve readabillty. Using
the "IS NOT EMPTY" and "IS EMPTY" logical expressions. ine can write

statements such as

IF KENNEL(FAFP) IS NOT EMPTY,


REMOVE THE FIRST DOG FROM KENNEL(FARM)
EL SE aeic

IF SEX(PERSOH)-'MALE- AND FAMILY(PERSON) IS EPPTY,


CALL BACHCLOR.ACTION GIVEN PERSON
ELSE

All tho s*atesmnts described thus far &Asumi that every set has
a full complement of owwership and emboerehip attributes, i.e., that

both first and last, predecessor sad successor poibters, asd c..nter
sad meamwership attributes are defiued. To perform all of the available
-233-

set manipulatitons, they must all be present. When set needs are moie
modest, sets with fever pointers can be designed, with a gain in
efficiency in set manipulations at the expense of some manipulative
power.
The sets pictured in all preceding illustrations contain all
possible pointers. Additionally, they rank on a fitst-in, first-out,
priority scheme, i.e., FILE LAST is the default condition. Other
rankings are possible. For examole, in a set defined by the declarations

EVERY COUNTRY OWNS AN ARMY


EVERY MAN HAS A HEIGHT AND A WEIGHT
AND BELONGS TO AN ARMY

we might want the various men in the army sets to be ranked by weight
or height, rather than by set et, rsnce time. Furthermore, we might
want this ranking to be in ascending or descending ordei. This can
be done by including a set definition atutement after the EVERY state-
ments that first mention a set, and after any attribute definition
statements that might be associated with the EVERY stateraer'. A set
definition statement, like an attribute definition atatemetnt, begini
with DEFINE. The following statements define the set ARMY as being,
respectively: (1) ranked in descending order by the HEIGHT attribute
of the fntities in it; (2) ranked in ascending order by tCese same
att.-ibutes; (3) ranked in descending order by the WEIGHT attribute
of the entities in it; (4) ranked in descending order by the HEIGHT
attributes, and, fcr those entities whose HEIGHT attributes have equal
value, ranked in ascending order by their WEIGHT attrlbut'!s.

(1) DEFINE ARMY AS A SET RANKED BY HIGH HEIGHT


(2) DEFINE ARMY AS A SET RANKED BY LOW HEIGKT
ý3) DEFINE ARMY AS A SET RANKED BY WEIGHT
(4) DEFINE ARMY AS A SET RANKED BY HIGH WEIGHT,
THEM BY LOW WEIGHT

Exasple ()' shovs that omission of the vords HIGH o:r LCW iar•,e,
HIGH. Example (4) shows how ranaings can be ascetdca, ,nc after
another, by THEN BY clauses to ,*solve ties vhen ranking %ttrP-!1tV%
are equal. As many THEN BY clawes car. So used as are .,eded 'n Any
given applicatior. A cosms must precede each THEN BY ,-!ause.
-234-

If a set is to be ranked only by entry time of entities into it,


a short form can be used. Depending upon whether the ranking gives
highest priority to the earliest or latest arrivel, the DEFINE state-
ment is written as:

(1) DEFINE ARMY AS A FIFO SET or


(2) DEFINE ARMY AS A LIFO SET
If form (1) is used, entitieb are put in sets on a first-in, first-out
basis; they are filed last as they are put in and removed in the order
in which they were filed. If form (2) is used, entities are put in
sets on a last-in, first-out basis.
In some cases, not all of the automatically defined set pointers
are needed. This is true in FIFO- and LIFO-definad •LU, where enti-
ties are never inserted in the middle of a set, but only at the begin-
ning or end. A FIFO set need have only first, last, and successor
pointers; a LIFO set need have only first and successor pointers.
FIFO and LIFO set organizations are shown in Fig. 4-10.
Since ranked sets are defined with respect to ranking values of
their members, it rarely, if ever, makes sense to use FILE BEFORE or
FILE AFTER in such sets. Doing so will, in fact, destroy the ranking
concept. A clause can be appended to a set declaration statement to
delete unused set attributes; any or all of the three owner-entity
and three member-entity attributes may be deleted. If the first-in-
set attribute is deleted, the "IS EMPTY" logical expression cannot be
used; if the membership attribute is deleted, the "IS IN set" logical
expression cannot be .ised. Table 4-5 on page 241 defines the state-
ments that cannot be used when ceitain set attributes are deleted.

The deletion clause is of the fcrin

WITHOUT attribute list ATTRIBUTES

Attribute list is a list of one or more of the letters F, L. P, S, N,


and M. The presence of a letter indicates that the attribute formed
by prefixing it and a period to the set name is not automatically
generated. For example, we might write the following statement
defining a LIFO set:
-235-

LIFO set FIFO set

Owner Entity Owner Entity

F. F.
L.

......................... ............... ........... ........ ................


Member Member
Entities Entities

FILE adds to FILE adds


this end. to this
REMOVE takesnend.
from this
end. S. S.

S S.

S. S.

REMOVE takes
from this end

S. 0 S. 0

Fig. 4-10 -- LIFO and FIFO set organizations

IJ
-236-

DEFINE ARRIVALS AS A LIFO SET WITHOUT L,P,N


AND MATTRIBUTES

The astute reader will note that while it is possible to delete all
attribuces, doing so completell destroys the concept of a set. The
programmer is cautioned against deleting set attributes without care-
fully considering the consequences (see Table 4-5, page 241).
When required, two or mcre sets having the same properties can
be declared in the same DEFINE statement. A list of set names can
appear after the word DEFINE, and the word SETS used instead of SET.

4-10 ENTITY CONTROL PHRASES

Two new forms of the FOR statement make it possible to step


through collections of entities, just as the FOR v - e fO e2 BY e
statement made it possible to step through successive elements of
arrays. One form deals exclusively with permanent entities and the
other deals with sets.
Permanent entities, having their attributes stored as arrays,
are indexed sequentially. The first entity of the permanent entity
class AUTO has index 1, the second 2, ... , the nth N.AUTO. To step
through a sequence of index numbers from 1 to N.entity for a particular
permanent entity class on.- writes

(1) FOR EACH entity or


(2) FOR EACH entity CALLED variable
Form (1) is equivalent to the statement FOR entity - 1 to N.entity,
where entity is the global variable with the same name as the entity
class. Thus, the statement FC., :-Ad- AUTO is equivalent to the state-
ment FOR AUTO - I TO N.AUTO. The words EVERY and ALL may be used in
place of EACH, if desired.
Form (2) is equivalent to the statement FOR variable - 1 TO
N.entity, where the variable named in the CALLED phrase, instead of
the global variable with the same name as the entity, is used to
receive the sequential index values. This variable can be global or
local. It cannot be subscripted.
"Regular" FOR statements and WiiH, UNLESS, WHILE, and UNTIL
-237-

statements can be appended to permanent entity control FOR phrases


as required.
The following statements illustrate a typical permanent entity
FOR phrase apylication: V
Program Preamble :

PERMANENT ENTITIES
EVERY MAN HAS A NAME, AND AN AGE

Main Program:

READ N.MAN
CREATE EVERY MAN

FOR EVERY MAN, READ NAME(MAN), AGE(MAN)

FOR EVERY MAN WITH NAME(MAN)="JOHN", DO


ADD AGE(MAN) TO SUM
ADD 1 TO N

LOOP

Experience has shown that some people would rather write FOR EACH
JOB, rather than FOR I = 1 TO N.JOB even if JOB has not been defined
as a permanent entity. That is, they prefer not to make up a local
variable name (I in this instance) just to step through a sequence of
values from 1 to N (N.JOB in this instance), but would rather use a
name that is easy to remember and has some meaning. To facilitate
this, the phrase

INCLUDE entity nxne list

can be appended to a PERMANENT ENTITIES statement, as in

PERMANENT ENTITIES INCLUDE MAN, COUNTRY AND FISH

This phrase defiL,,• the listed names as permanent entities with-


out attributes, but with the associated global variables entity and
N.entity. The above statement defines the global variables MAN, N.MAN,
-238-

COUNTRY, N.COUNTRY, FISH, and N.FISH and permits the statements

FOR EVERY MAN


FOR EACH COUNTRY and
FOR ALL FISH

to be used. The following short example illustrates why this might


be a useful shorthand:

Program Preamble:

PERMANENT ENTITIES INCLUDE ELEMENT

Main Program:

READ N.ELEMENT
RESERVE LIST(*) AS N.ELEMENT
FOR EACH ELEMENT, LET LIST(ELEMENT)- 1

It should be clear that such a statement is impossible for temporary


entities. Scattered throughout memory, rather than stored sequen-
tially, temporary entities cannot be indexed by ordinal numbers; they
can only be pointed to by set pointers. To process all the temporary
entities of a given class, the entities must be stored in a set as
they are created, and must be processed by a statement that deals
with the set. This statement, which by its nature deals with both
permanent and temporary entities, has two basic forms:

(a) FOR EACH variable OF set


(bl) FOR EACH variable FROM arithmetic expression OF set
(b2) FOR EACH variable AFTER arithmetic expression OF set

Form (a) selects entities that are members of an indicated set


in order of their ranking and assigns their identification number to
a named variable. If the set is empty, all of the statements con-
trolled by the FOR statement are bypassed. The control variable can
be either local or global. It cannot be subscripted.
Form (bl) does the same task as form (a), except that it starts
with the set member identified by the indicated expression. Form
(b2) is similar to (bl), but starts with the set member that follows
the identified member. If the identified member is not in the set
(denoted by a "no" in its membership attribute), the program terminates
with an error meesage.
-239-

In forms (a) the words EVERY and ALL can be used instead
and (b),
of EACH, and the words IN, ON, and AT used as synonyms for OF.
To step backward through a jet, the phrase

IN REVERSE ORDER
is placed after the set name. Set control can range from simple state-
ments such as

FOR EVERY JOB IN QUEUE

to complicated statements such as

FOR ALL FISH AFTER MINNOW(I) IN POND IN REVERSE ORDER

Since many variations of rOR statements are possible, a few illus-


trations follow. In these illustrations, we assume that permanent
entities with identification numbers i, 2, 3, 4, 5, and 6 are filed
in a set in the order of 1, 3, 2, 4, 6, 5. They may have arrived in
this order and be stored as FIFO, or they may have been ranked on
some attribute value; the method of ranl ,T is not important in this
example. Table 4-4 states different control statements and indicates
the identification number sequence of entities that are passed on to
the controlled statements by each. The entities are filed in a set
named FILE; the local variable J is used within the control loop for
the selected identification numbers.
Section 2-07 gave the expansion of the "regular" FOR statement
into simpler SIMSCRIPT II statements so that persons wishing to per-
form atypical operations within the control of a FOR statement will
know how the statement works and avoid writing incorrect programs.
The following program is a prototype of the code generated for state-
ments of the form
-24'0-

Table 4-4

ILLUSTRATIVE SET CONTROL STATEMENTS

Identification
Control Statement Number Sequence

FOR EACH J IN FILE 1 3 2 4 6 5


FOR EACH J FROM 4 IN FILE 4 6 5
FOR EACH J AFTER 4 IN FILE 6 5
FOR EACH J IN FILE IN
REVERSE ORDER 5 6 4 2 3 1
FOR EACH J FROM 4 IN FILE
IN REVERSE ORDER 4 2 3 1
FOR EACH J AFTER 4 IN FILE
IN REVERSE ORDER 2 3 1
FOR EACH J IN FILE UNTIL J=3 1
FOR EACH J IN FILE IN REVERSE
ORDER UNTIL J=3 5 6 4 2
FOR EACH J FROM 2 IN FILE
UNTIL J=6 2 4
FOR EACH J IN FILE WITH J#5 1 3 2 4 6

FOR EACH V OF set t, DO statement group LOOP

LET V = F.set
GO TO L.2
'L.1° LET V= L.4
'L.2' IF V- 0 GO TO L.3
ELSE LET L.4- S.set(V)

statement grouv

GO TO L.1
'L.3'

A comparison of this program with that of Sec. P,-O7 reveals that the
two are analogous. The first LET statement picks up the initial item
in the iteration sequence; the statement labeled 'L.2' checks to see

t aet iepresents a subscripted or unsubscripted set. If subscripted,


F.set must have the same number of subscr:Lpts.
-241-

if the sequence has ended; and the statement labeled 'L.1' sets the
control variable to a new vflue for the next iteration. Variations
of the FOR phrase produce variations in this prototype; for example,
writing FOR EACH V FROM W OF set changes the first statement to
LET V- S.8et(W). Adding an IN REVERSE ORDER clause changes the LET
statement following the ELSE statement to LET LA4 - P.aet(V), etc.
The consequences of particular statements within a FOR phrase control
loop can always be determined by constructing the program generated
by the specific FOR phrase and analyzing its relation to the state-
ments involved.
Table 4-5 lists the set attributes that are required for the
different set operations described.

Table 4.-5

REQUIRED SET ATTRIBLTES

Statement Attributes Required


F L P S M N
FILE in a ranked set x x
FILE FIRST x x
FILE LAST x x x
FILE BEFORE y x x
FILE AFTER x x
REMOVE FIRST x x
REMOVE LAST x x x x
REMOVE soecific x x x
IS EMPTY x
IS IN set + X
Automatic checking x
FOR EACH V IN set x x
FOR EACH V IN set IN REV. X x
FOR EACH V FROM W IN set I x
FOR EACH V FROM W IN set IN REV. x
FOR EACH V AFTER W IN set
FOR EACH V AFTER W IN set IN REV. X

±
Following sections dtscribe automatic set diagnostics
performed only when a membership attribute is included.
-242-

4-11 COMPOUND ENTITIES

At times it is convenient for several entities jointly to have


attributes and own sets. Such entities are called compound entities.
Statements such as

PERMANENT ENTITIES
(1) EVERY MAN AND WOMAN OWNS A FAMILY AND HAS
A BANK.ACCOUNT
(2) EVERY CITY,COUNTY,STATE HAS A CENSUS
(3) EVERY MODELCOLORYEAR,MFG HAS A SALES.VOLUME
define compound entities composes of 2, 3, and 4 permanent entities,
respectively. The first defines three two-dimensional arrays:
F.FAMILY, L.FAMILY, and BANK.ACCOUNT, e&ch dimensioned as N.MAN BY
N.WOMAN. The second defines a three-dimensional array CENSUS dimen-
sioned as N.CirY BY N.COUNTRY BY N.STATE. The fourth defines a four-
dimensional array dimensioned in a similar way. Compound entities
are defined by statements of the form

EVERY compound entity name list HAS attribute name list AND OWNS
set plow list.

As in the case of individual entity definitions, HAS and OWNS clauses


can appear in the same or different statements. The word HAVE can be
used for HAS and OWN for OWNS. Compound entities cannot belong to
sets. By definition, the individual entities of which compound en-
tities are composed must exist, e.g., if there is a compound entity
MAN AND WOMAN there must be an elitity MAN and an entity WOMAN.
A oompoumln entity none Zist is a list ef entity names that hive
either been declared previously in EVERY or INCLUDE statements, or,
by their presence in a compound entity declaration, are declared as
entities of the type specified in the current background condition.
i.e., by the last PEMANENT ENTITIES or TEMPORARY ENTITIES statement.
Three kinds of compound entities are possible: those composed ex-
clusively of permanent entities; those composed exclusively of tem-
porary entities; gnd those composed of both permanent and temporary
entities.
Members of sets owned by compound entities can be either permanent
-243-

or temporary entities. Set membership is declared as usual. More-


over, "compound sets" can have any of their six set attributes deleted
and be defined as FIFO, LIFO or RANKED. The following statements
might appear in & program in conjunction with declaration (1) above:

TEMPORARY ENTITIES
EVERY CHILD BELONGS TO A FAMILY AND HAS AN AGE
DEFINE FAMILY AS A SET RANKED BY AGE WITHOUT N AND M ATTRIBUTES

Attributes of compound entities and sets owned by compound en-


titles are subscripted. Subscripting takes place in the order in
which compound entities are defined. Thus, in the statements

LET BANK.ACCOUNT(IJ) - 1000


FILE rHIS CHILD IN FAMILY (MAN.WOMAN)

the variables I and MAU can range from 1 to N.MAN, and the variables
J and WOMAN can range from I to N.WOMAN.
Arrays are allocated to "permanent" compound entities when their
individual entities are created. While it is usual, it is not ncces-
-'y that they be created together. Given the declarations

PERMANENT ENTITIES
EVERY MAN HAS A JOB AND A SALARY
EVERY WOMAN OWNS SOME JEWELRY
EVERY MAN AND WOMAN OWNS A FAMILY AND HAS A
BANK.ACCOUNT

the statement

CREATE EACH MAN AND WOMAN

reserves arrays for the attributes of MAN and WOMAN, and the compound
entity MAN,WOMAN. The CREATE statement is in fact translated into
several RESERVE statements:

RESERVE JOB(') AND SALARY(-) AS N.MAN


RESERVE F.JEWELRY('), L.JEWELRY(*) AND N.JEWELRY(')
AS N.W`OFAN
RESERVE F.FAMILY(',*), L.FAMILY(',), N.FAMILY(',') AND
BANK.ALCOUNT(*.,) AS N.MAN BY N.WOb6AN

Attributes of permanrnt ,ompound entities :an he released hy

regular RELEASE btateamers such aq

RELEASE 8ANK.ACCOUNT
-244-

Compound entities composed exclusively of temporary entities, or


of rixtures of pernanent and temporary intities, look the same as
"permanent" compound entities but function differently. The difference

lies in the fact that all attributes of "mixed" or "temporary" com-


pound entities are funztions; they have no storage allocated to them.

They cannot be created or destroyed, s& can (and indeed must) the
entities of which they are composed. A routine must be written for
each compound at.tribute (including set pointers) of this type that
accepts the attribite indices as argumants and re:urns a single value --

an attribute value or a set pointer. Thus, the declaration

-VERY JOB.MAN tiAS AN INFLUENCE FUN•CTION

where JOB and MAN are temporary entities, defines INFLUENCE as a


fun,ztion having the background mode. This function can be further

defined, as in

DEFINE INFLUENCE AS A REAL FUNCTI)N

if necessary. When a statement like LC"T T- TIME*INFLUENCE(JOB,PERSON)


is executed, the rouitine INFLUENCE is .- alled with the arguments JOB
a'r PERSON -- two identification numbers of temporary -ntities. The

ro,.ine must perform a task such as:

ROUTINE INFLUENCE (IJ)


DEFINE I AND J AS INTEGER VARIABLES
IF STATS(J) - 5M AND PRIORITY(I) - PM
RETURN WITH(STArUS(J)/SM)*(PPIoRIOIY(I)/PM)
ELSE RETURN •:TH 1
END

Preceding ,,!c,_ifls ,. low


thicrihattribures are ý!rfinv' and
touched •yn t'•,ir use. Kxa.pplrs showed tr'at attribnutcs 'look 1ike sub-

scriptJ variAbles whn thvy arppear in programs; every attribute


reference is of the forz

For attributes of individuia. *tiri,%, '.ttv


*,e i.A-n.tif-cAtion is

An i
01 0Y 1dentft-AtIMn rr or atrib:,-. of -omc",r.
-245-

entities, the entity identification is a list of index or identifica-


tion numbers.
The automatic definition of global variables with the same names
as declared entities was also discussed. They were used in minimizing
the need for local variables in stuations like:

CREATE A SHIP
READ NAME(SHIP), TONNAGE(SHIP),...,SPEED(SHIP)

When used in this manner, attribute subscripts are stated explicitly;


identification or index numbers are used to access attribute valu-.i.
The above statements are functionally equivalent to the statements:

CREATE A SHIP CALLED S


READ NAME(S), TONNAGE(S),..., SPEED(S)

Since all items indexed by entity names (attributes and sets)


are declared in the program preamble, it is possible to declare a
default or implied subscript if one is omitted frona an attribute or
set reference, An impZieJ 8ubsacri.t is a global variable having the
same name as the entity associated with the attribute or set refer-
enced. In the case of compound entitie3, subscrints are implied in
the order they appear in the defining EVERY statement. For obvious
reasons, common aLtributes cannot have imrplied subscripts. Some
example; of entity dcfinitions and Implied subscripts follow:

(1) Declaration:

PERMANENT ENTITIES
EVERY MAN HAS AN AGE

Use:

LET AGE- 1 is eq,;ivaient to LET AG_(MAX:,- 1

Whenever the attribute AGE ap;-ears wit-icur an entity reference, the


global variab' 'AN 1if ugrd az an Ident1iU-tion nmlbcr.
(2) .oc lArat km :

TEMPORARY ENTITIES
EVERY PROGRAM COWS SCf# LABEL•
EVERY LABEL BEL-OGS To SOWE LABELS
-246-

Use:

CREATE A PROGRAM

CREATE A LABEL CALLED EXIT


FILE EXIT IN THE LABELS

FILE EXIT IN THE LABELS is equivalent to FILE EXIT IN THE LABELS(PROGRAM).


(3) Declaration:

PERMANFNT ENTItIES
EVERY CITYSTATE HAS A DOPULATION

Use:

LET POPULATION = 400000 is equivalent to


LET POPULATION(CITY,STATE) = 400000
LET POPULATIGO1(NEW.YORK) = 8000000 is equivalent to
LET POPULATION (NEW.YORK,STATE) = 8000000

Imp!i.ed subscripts cannot be used in free-form READ statements


to input attributes of permanent entities, as the form READ attri-
bute inpliev input j4 the entire attribute array.

4-13 DiSPLAYING ATTRIBUTE VALUES

Specl attribute values can be output by conventional PRINT


and WRITE statements. An attribute reference appearing in an output
list callh for the reuit2i7al and display of a single value just as a
subscripted variable or function reference does. Some examples of
attributes used ir PRINT and WRITE statements are:

(1) PRINT 1 LINE WITH POPULATION(STATE) AS FOLLOWS


POPULATION IS *******
(2) WRITE I, S(X), INDEX(I), NAME(INDEX(I)) AS 3 I 5, A 10
(3) FOR EACH CARROT IN BUNCH, WRITE LENGTH(CARROT) AS 1 4

Implied subscripts can be used in PRINT and WRITE state ments, as


well as In computational statements. Attribute& declared by the
statement

PERMANENT ENTITIES
EVERY BOOK HAS A PAGE.COUNT, A SUBJECT AND AN AUTHOR
-247-

can be displayed by the statement

FOR EVERY BOOK, WRITE PAGE.COUNT,SUBJECT AND AUTHOR AS I 4, 2 A 10

The LIST statement can be used to display all the attributes of


an entity without writing all their names. Three forms are available:

(1) LIST ATTRIBUTES OF entity CALLED arithmetic expression

displays the attributes of the particular entity referenced. The


statement can be used for both permanent and temporary entities. The
format used is that employed for displaying values of expressions or
unsubscripted variables. A short form

LIST ATTRIBUTES OF entity


displays the attributes of the entity whose index or identification
number is contained in the global variable with the same name as the
entity.

(2) LIST ATTRIBUTES OF EACH entity

displays the attributes of all the entities in a permanent entity


cla3s. The format used is that employed in listing one-dimensional
arrays. If only one attribute of a permanent entity class is to be
printed, it must be done by referencing the pointer to the array con-
taining the attribute values, e.g., by a statement of the fc m

LIST attribute

(3) LIST ATTRIBUTES OF EACH entity IN set

dibplays the attributes of all the entities, permanent or temporary,


filed in an indicated set. Since only one heading is printed, the
labeled output is only meaningful for sets with one class of entity
filed in them.
The ust of each of these statement forms is illustrated in the
following examples:

Entity and set declaration:


I
-248-

PERMANENT ENTITIES
EVERY COUNTRY OWNS A FLEET
EVERY SHIP HAS A NAME , BELONGS TO A FLEET
AND OWNS A CREW
TEMPORARY ENTITIES
EVERY MAN HAS A SERIAL.NO, A RATING, A SKILL
AND BELONGS TO A CREW
Use of LIST statements:

(a) REMOVE THE FIRST MAN FROM CREW(VESSEL)


LIST ATTRIBUTES OF MAN
(b) FOR EACH MAN IN CREW(SHIP) WITH RATING > 4,
FIND PERSON = THE FIRST MAN
LIST ATTRIBUTES OF MAN CALLED PERSON
(c) READ N.COUNTRY AND N.SHIP
CREATE EACH COUNTRY AND SHIP

LIST ATTRIBUTES OF EACH COUNTRY


(d) LIST ATTRIBUTES OF EACH MAN IN CREW(QUEEN.MARY)
(e) LIST ATTRIBUTES OF SHIP CALLED 4
(f) LIST NAME, (VALUE(I) + COST)/RATEATTRIBUTES OF SHIP CALLED TITANIC

4-14 SOME SAMPLE PROGRAMS

The programs in this section illustrate the concepts and state-


ments described thus far. The reader is urged to follow them closely
and identify the features used in each of them. A useful exercise is
the reformulatior and reprogramming of the examples using different
concepts and statements.

4-14-1 An Inventory Control Progrwa

PREAMBLE NORMALLY MODE IS INTECER


PERMANENT ENTITIES
EVERY ITEM HAS A RP ''REORDER POINT'',
AN SCL ''STOCK CONTROL LEVEL'',
A STOCK ''AMOUNT ON HAND'',
A DUE.IN ''AMOUNT ORDERED, NOT RECEIVED'',
A DUE.OUT ''AMOUNT OF BACK ORDERS'
END
-249-

MAIN READ N.ITEM CREATE EACH ITEM


FOR EACH ITEM, READ RPSCLSTOCK,DUE.IN,DUE.OUT
'READ' IF DATA IS ENDED, GO TO FINiISH ELSE
READ TRANSACTION, ITEM, QUANTITY
IF TRANSACTION= 1 ''PROCESS AN ORDER

IF STOCK GE QUANTITY, SUBTRACT QUANTITY FROM STOCK


GO TO REORDER.CHECK
OTHERWISE ''INSUFFICIENT STOCK'' ADD QUANTITY-STOCK TO DUE.OUT
LET STOCK=O
'REORDER.CHECK'
IF STOCK + DUE.IN- DUE.OUT LE RP,
LET ORDER= SCL+DUE.OUT-DUE.IN-STOCK
PRINT 1 LINE WITH ORDER,ITEM THUS
ORDER *** UNITS OF STOCK NO. *
ADD ORDER TO DUE.IN
REGARDLESS GO READ
OTHERWISE ''PROCESS A RECEIPT''
SUBTRACT QUANTITY FROM DUE.IN
IF DUE.OUT > QUANTITY, SUBTRACT QUANTITY FROM DUE.OUT
GO TO READ
ELSE ADD QUANTITY-DUE.OUT TO STOCK
LET DUE.OUT=O GO TO READ
'FINISH'
LIST ATTRIBUTES OF EACH ITEM
STOP
END
T1wo good exercises for the reader are: (1) identify each customer
and generate a shipment notice for each order, and (2) keep track of
to whom stock is owed (backorders) and ship it out according to some
rational policy.

4-14-2 Two IlZustrations of Set Ranking by Function Attributes

As dcscribed in Sec. 4-09, sets are normally ranked on either


the order in which entities are filed in them (FIFO and LIFO) or on
attribuces of their member entities. In the latter case, while cas-
cading can be used to resolve ties, only simple single-attribute
ranking comparisons can be made. Complex ranking comparisons can be
devised using function attributes as ranking variables. The following
short program illustrates how a function attribute can be used to
define a ranking variable that is the weighted average of several
attribute values.
-250-

PREAMBLE
TEMPORARY ENTITIES
EVERY JOB HAS A LABOR.COST, A MATERIAL.COST,
AN OVERHEAD, A PROFIT, A RANKING FUNCTION
AND BELONGS TO A QUEUE
PERMANENT ENTITIES
EVERY MACHINE OWNS A QUEUE
DEFINE QUEUE AS A SET RANKED BY HIGH RANKING
END
MAIN
READ N.MACHINE CREATE EVERY MACHINE
'NEW.JOB' CREATE A JOB
READ LABOR.COST, MATERIAL.COST, OVERHEAD
AND PROFIT ''INITIAL VALUES''
READ MACHINE ''TO DO THIS JOB
FILE JOB IN QUEUE (MACHINE)

REMOVE JOB FROM QUEUE (MACHINE)

GO TO NEW.JOB

END

ROUTINE FOR RANKING GIVEN J


DEFINE J AS AN INTEGER VARIABLE
RETURN WITH (LABOR.COST * 2 + MATERIAL.COST * 3
+ OVERHEAD + PROFIT * 4) / 10
END
The preamble defines RANKING as a function attribute of JOB and
as the attribute by which jobs are ranked when they are filed in a
set QUEUE(M). The routine RANKING provides a procLt-re for computing
a ranking value; the routine is invoked each time a JOB is filed. It
is used to compute a ranking value for the JOB being filed, and for
all the jobs against which this job's ranking value must be compared
in order to insert it properly.
A somewhat different use of fu;nction attribute is found in the
following program, which uses an attribute of the first member of a

LI
-251-

set owned by an entity as the ranking value for that entity's filing
in another set.

PREAMBLE
TEMPORARY ENTITIES
EVERY JOB OWNS A ROUTING, BELONGS TO A QUEUE AND HAS A VALUE
EVERY PATH HAS AN ORIGIN, A DESTINATION, A RANKING FUNCTION
AND A DISTANCE AND BELONGS TO A ROUTING
PERMANENT ENTITIES
EVERY MACHINE OWNS A QUEUE
DEFINE QUEUE AS A SET RANKED BY HIGH RANKING
DEFINE ROUTING AS A SET RANKED BY LOW DISTANCE
DEFINE RANKING AS AN INTEGER FUNCTION
END

ROUTINE FOR RANKING(J)


DEFINE J AS AN INTEGER VARIABLE
RETURN WITH ORIGIN(F.ROUTING(J))
END

4-14-3 A bata Analysis Application


PREAMBLE
PERMANENT ENTITIES
EVERY COUNTY HAS A NAME AND A STATE
EVERY YEAR HAS A NATIONAL.GNP, A RC.PRICE.RC
EVERY COUNTY, YEAk HAS A POPULATION, A LOCAL.GNP, AND
A LOCAL.GNP.PERCAPITA
EVERY YEAR, CAR HAS A NATIONAL.SALES, A PRICE
AND A SALES.GNP.RC
EVERY COUNTY,YEAR,CAR HAS A LOCAL.SALESAND A
LOCAL.SALES.PERCAPITA
DEFINE NAME AND STATE AS ALPHA VARIABLES
DEFINE LOCAL.GNP.PERCAPITA AND LOCAL.SALES.PERCAPITA
AS REAL VARIABLES
END

MAIN READ N.COUNTY, N.YEfR, N.CAR


CREATE EVERY COUNTY, YEAR AND CAR
FOR EVERY COUNTY, DO READ NAME AND STATE
ALSO FOR EVERY YEAR,
READ POPULATION, LOCAL.GNP
LOOP
FOR EVERY YEAR, DO READ NATIONAL.GNP
ALSO FOR EVERY CAR,
READ NATIONAL.SALES AND PRICE
LOOP
-252-

FOR EVERY COUNTY, FOR EVERY YEAR, FOR EVERY CAR,


READ LOCAL.SALES
' 'COMPUTATIONS' '
FOR EVERY COUNTY, FOR EVERY YEAR, DO
LET LOCAL.GNP.PERCAPITA= LOCAL. GNP/POPULAT ION
FOR EVERY CAR,
LET LOCAL.SALES. PERCAPITA= LOCAL.SALES/POPULATION
LOOP
FOR EVERY CAR, FOR EVERY YEAR, DO
FOR EVERY COUNTY, DO
COMPUTE A= SUM, B= SUM.OF.SQUARES OF LOCAL.GNP.PERCAPITA
COMPUTE C= SUM OF LOCAL.SALES.PERCAPITA
COMPUTE D= SUM OF IOCAL.GNP.PERCAPITA * LOCAL.SALES.PERCAPITA
LOOP
LET SALES.GNP.RC = (N.COUNTY*D-A*C) / (N.COUNTY*B-A**2)
LOOP
FOR EVERY YEAR, DO
FOR EVERY CAR DO COMPUTE A=SUM,B=SSQ OF PRICE
COMPUTE C=-SUM OF SALES.GNP.RC
COMPUTE D=SUM OF PRICE*SALES.GNP.RC
LOOP
LET RC.PRICE.RC= (N.CAR*D-A*C)/(N.CAR*B=A**2)
LOOP
LIST SALES.GNP.RC, RC.PRICE.RC AND NATIONAL.GNP

STOP
END
This program reads data on auto sales and prices for different
population units, and computes regression coefficients that allow the
following graphs to be drawn:

for a given year and car

F-

0ý / .
.LJ
,a.
S 6 NOTE: Fach point
B represents a county

LOCAL.GNP.PERCAPITIA

V I
-253-

for a given year

w 0

NOTE: Each point


represerz a car

PRICE

The reader should (1) ensure that he understands the computations


the program performs and the reason why the individual loops are
written as they are, and (2) rewrite the program where he can to make
it more efficient.

4-14-4 An Analysis of Prime Nuwnbers

PREAMBLE NORMALLY MODE IS INTEGER


THE SYSTEM OWNS SOME PRIMES
TEMPORARY ENTITIES
EVERY PRIME HAS A VALUE AND BELONGS TO SOME PRIMES
END

MAIN READ N
FOR 1= 2 TO N. DO ''CREATE PRIME NUMBERS''
FOR EACH PRIME IN PRIMES WITH MOD. F(I,VALUE) 0,
FIND THE FIRST CASE
IF NONE, CREATE A PRIME LET VALUE = I
FILE PRIME IN PRIMES
REGARDLESS
LOOP
FOR EACH I OF PRIMES WITH S.PRIMES(1) NE 0,
COMPUTE MAX= THE MAX(1) OF VALUE(S.PRIMES(I))-VALUE(1)
PRINT 2 LINES WITH N,VALUE(MAX),VALUE(S.PRIMES(MAX)) THUS
MAXIMUM GAP AMONG THE FIRST **** PRIMES
OCCURS BETWEEN **** AND ****
STOP
END
-254-

4-14-5 Dynamic Definition and Use of Array Attributes

The following statements illustrate how to create, use, and


destroy array attributes:

Declaration:

PREAMBLE
TEMPORARY E1TITIES
EVERY ENTITY HAS AN ARRAY
DEFINE ARRAY AS AN INTEGER VARIABLE
DEFINE DUMMY AS A 2-DIMENSIONAL ARRAY
END

Creation:

CREATE AN ENTITY
RESERVE DUMMY(*,*) AS 3 BY N
LET ARRAY(ENTITY) = DUMMY(*,*)
LET DUMMY(W,*) = 0

Use:

FILE ENTITY IN SET

REMOVE THE LAST ENTITY FROM THE SET


LET DUMMY(*,*) = ARRAY(ENTITY)
FOR I= 1 TO DIM.F(DUMMY(*,J)), READ DUMMY(I,J)
Destruction:

REMOVE ENTITY FROM SET


LET DUMMY(*.*) = ARRAY(ENTITY)
RELEASE DUMMY
DESTROY ENTITY

4-14-6 Using "Optional" Attributes

In certain situations, especially ones involving data processing,


entities are defined that have a large number of attributes, many of
which are constants. For example, in census records the code n/a
(not applicable) appears in many places. When, in such situations,
it i: necessary to conserve the amount of space allocated to individual
entity records, function attributes can be used to define "optional
attributes." These are actually entities stored in a special met only

U
-255-

if their values differ from specified default values. Thus, if the


optional attribute RAPID.TRANSIT is other than 0 for a particular
city, a record for it will appear in that city's optional attribute
set. Otherwise. the value of RAPID.TRANSIT would be found in the
default list (DEFAULT(1)=O).
The following declarations and programs show how to set up and
use optional attributes.

Declarations:

PREAMBLE
TEMPORARY ENTITIES
EVERY CITY OWNS SOME OPTIONS. HAS A NAME,
A POPULATION, A STATE AND AN OPTIONAL
FUNCTION
EVERY OPTION HAS A VALUE AND A CODE AND
BELONGS TO SOME OPTIONS
DEFINE NAME AND STATE AS ALPHA VARIABLES
DEFINE WHICH AS A "GLOBAL'' VARIABLE
DEFINE DEFAULT AS A I-DIMENSIONAL ARRAY

END

Function attribute definition:


ROUTINE OPTIONAL (J)
DEFINE I AND J AS INTEGER VARIABLES
FOR EACH I IN OPTIONS(J),
WITH CODE(1) - WHICH,
FIND THE FIRST CASE
IF FOUND, RETURN WITH VALUE(1)
ELSE RETURN WITH DEFAULT(WHICH)
END

Progra& initialization to set up optional attribute structure:

MAIN

READ N RESERVE DEFAULT(') AS N


READ DEFAULT ''LIST OF DEFAULT VALUES''
-256-

CREATE A CITY
UNTIL MODE IS ALPHA,
CREATE AN OPTION
READ CODE AND VALUE
FILE OPTION IN OPTIONS
LOOP

END

Program a--atements that employ optional attributes:

LET WHICH - 1 ''INDICATING THE FIRST


" OPTIONAL ATTRIBUTE

LET X - OPTIONAL(CITY)
if an entity CITY has an entity filed in
its OPTIONS set with CODE - 1, X is set
to the VALUE of the entity
if an entity CITY has no such entity filed
in OPTIONS, X ia set to DEFAULT(1)

The program can be maude even more straightforward if functions


are used to define the optional attributes themselves. If RAPID.TRANSIT
ia an optional attribute of CITY, it can be defined and used by the
following statements:

DEFINE RAPID.TRANSIT AS AN INTEGER FUNCTION


ROUTINE RAPID.TRANSIT(CITY)
DEFINE CITY AS AN INTEGER VARIABLE
LET WHICH - 1
RETURN WITH OPTIONAL(CITY) -
END

The following diagram shovs the record structura for rtemporary


entity of type CITY that has several "normal attributes" and %everal
"optional attributes":

I
-257-

CITY

-F.OPTIONS -67 000 000


L.OPT7ONS 1 1 is the code for
N.OPTIONS P.OPTIONS RAPID.TRANSIT
NAME SOPTIONS

STATE 3 500 000

4 4 is the code for


(P.OPTIONS - EDUCATION.EXPENSE

2 0.

3 I00ý 257 532 000


57 57 is the code for
. -P.OPTIONS MUNICIPAL.DEBT
•. S.OPTIONS

97 200
98 10
99 4510
100 -1

4-15 DELFTION OF SET ROU'TINS

Certain routines are automatically generated for each defined


set during the processing of a program preamble. Sets.declared aa
FIFO (explicitly or implicitly), LIFO, or RANKED require 'ifferent

routines to perform their operations. Each generated routine is


tailored to individual program specifl.:-Ations reflecting such things
as set attribute deletions and cascaded set rankings.
The most generally defined set, an unranked one declared as
either FIFO or LIFO, has seven routines generated for it. Four are
for filing and three for reryving. The routines are named, and their
functions stated in Table 4-6.
-258-

Table 4-6

SET MANIPULATION ROUTINES

Routine Generated Name Function

F.le first A.set Files an entity first or ranked


File last B.set Files an entity last
File before C.set Files an entity before a specified
entity
File after D.set Files an entity after a specified
entity
Remove first X.set Removes the first entity
Remove last Y.set Removes the last entity
Remove specific Z.set Removes a specified entity

A set declared by the statement

DEFINE QUEUE AS A FIFO SET

thus has seven routines, A.QUEUE, B.QUEUE, ... , Z.QUEUE generated for
it.
Ranked sets, by their definition, do not permit filing first,
last, or before or after a specific entity without attention to the
specified set ranking. Hence, ranked sets generate four routines,
there being only one file routine.
In addition, certain set operations are impossible if specific
set attributes are not present. For instance, filing before is
impossible in a LIFO set if the predecessor attribute has been deleted.
Tablc 4-7 shows the set attributes that must be present for the
indicated set operations to be performed.
Since all set attributes are not required for all set operations,
Table 4-7 can be used to determinte which attributes to delete in
ord a save memory space. For example, if a program only files
an( oves first, the set attributes L and P can be deleted without
pe t. If they are not deleted, the generated programs keep track
of update them anyway.
pecific set routines can also be deleted to conserve nmemory
s when their associated operations are not used in a program.
S

-259-

Table 4-7

SET OPERATION-SET ATTRIBUTE RELATIONSHIPS

Set Operation Set Name Required Set


Mnemonic Prefix Attribute
FF A. F,S
FL B. F,L,S
FB C. F,S,P
FA D. F,S
RF X. F,S
RL Y, F,L,S,P
kS Z. F,S,P

To do so, a list of the set cperation codes shown in Table 4-7 is


attached to a DEFINE SET statement in the following form:

,WITHOUT set operation code list ROUTINES

The come, is optional. A typical program might contain the statement

DEFINE QUEUE AS A FIFO SET WITHOUT P AND N


ATTRIBUTES AND WITHOUT FB, FA AND RS ROUTINES

In sophisticated programs wherein a programmer wants to use set


statements but wants to provide his own set operation routines, all
seven routines can be deleted. The codes F and R delete the four file
and three remove routines, respeczively. A complete range of set
specifications is thus possible. Mere mention of a set name in EVERY
statements calls for all three set attributes for the owner and member
entities, and all seven set routines. Additional definition in a
DEFINE SET statement can selectively delete set attributes and set
routines. The extreme statement

DEFINE set AS A SET WITHOUT F,L,P,S,M AND N


ATTRIBUTES WITHOUT F AND R ROUTINES

removes all mechanisms that make set operations possible.

* 4-16 LEFT-HANDED FUNCTIONS

Functions are normally thought of as "right-handed," in the sense


that they appear on the right-hand side of the equal sign in assignment
-260-

statements. They are used for computing values, rather than for
storing them.
One example of a right-handed SIMSCRIPT II function is OUT.F,
which is used to access characterr in the current output buffer (see
Sec. 3-11). The statement LET A = OUT.F(1), where A is an ALPHA
variable, extracts the first character from the current output buffer
and assigns its value to A. The single character is left-adjusted
within A and followed by blanks.
Defining a function as "left-handed" indicates that it receives
values, rather than that it computes them. SIMSCRIPT II allows the
function OUT.F to be used in both a right-handed and left-handed manner.
LET OUT.F(1)=A takes the leftmost character from the ALPHA variable A
and stores it in the first position in the current output buffer.
Any function can be defined to be used in both a right- ane left-
handed manner, i.e., to compute a value, the right-handed version of
the routine is called; when a reference is made in a left-handed manner,
i.e., to store a value, the left-handed version is called.
No Pew concepts or statements are invclved in the definition of
right-handed routines, for all the functions dealt with thus far have
been right-handed. All of the by now familiar declarative forms

ROUTINE name
ROUTINE name GIVEN argument
ROUTINE name (argument Zist)
indicate that the statements that follow, up to the statement END,
define a computational process, hence, a right-handed function. In
programs that use both right- and left-handed functions, the word
RIGHT may be put before ROUTINE, bt-t this is optional.
A left-handed function is headed by one of the forms of the
ROUTINE statement shown above, preceded by the word LEFT, as in

LEFT ROUTINE ACCESS GIVEN I AND J and


LEFT ROUTINE ALLOCATE
In addition to the usual mechanism for transmitting input argu-
ment values to a function when it is called, a left-handed function
must have a way of receiving a right-hand-side value. A statement
of the form
-261-

ENTER WITH variable

must be the first executable statement in every left-handed routine.


It specifies that the value "computed on the right" is to be stored
in the named variable, which can be local or global, unsub3cripted,
subscripted, or an attribute, for use within the routine. From there
on, a left-handed routine functions exactly like any other program;
it can store the value, perform computations with it, execute input-
output statements, etc. The following example illustrates the defini-
tion and use ef right- and left-handed routines:

The cuirputational section of this program (MAIN) seems to deal


with simple subscripted variables. Actually, the surrounding
routines and the preamble define the data structure dealt with.
In this sense, the program is independent ol. the structure used
for storing and analyzing its data.

PREAMBLE
THE SYSTEM OWNS SOME DATA
TEMPORARY ENTITIES
EVERY SAMPLE HAS A VALUE AND BELONGS TO SOME DATA
DEFINE X AS A REAL FUNCTION
DEFINE VALUE AS A REAL VARIABLE
END

MAIN
READ N FOR I=1 TO N, READ X(I)
FOR 1- 1 TO N-1, WITH X(I) <2*X(1+1)
COMPUTE M= AVG, V= VARIANCE, K= NUMBER OF XtO)**2
LIST K,M,V
STOP
END
RIGHT ROUTINE X(I)
DEFINE I,J,S AS INTEGER VARIABLES
IF I > N.DATA.
PRINT 1 LINE WITh I THUS
MEMBER *** OF COLLECTION AX DOES NOT EXIST
STOP
ELSE
IF 1=1, RETURN WITH VALUE(F.DATA)
ELSE LET S=S.DATA(F.DATA)
FOR J= 1 TO 1-2, LET S-S.DATA(S)
RETURN WITH VALUE(S)
END
-262-

LEFT ROUTINE X(I)


DEFINE I,J,S AS INTEGER VARIABLES
DEFINE A AS A REAL VARIABLE
ENTER WITH A
IF N.DATA=I-1.CREATE A SAMPLE CALLED S
FILE S LAST IN DATA
GO PLACE
ELSE IF N.DATA < I-1, PRINT 2 LINES WITH I,N.DATA THUS
TRYING TO CHANGE THE ***TH VALUE IN A COLLECTION
WITH ONLY *** MEMBERS
STOP
ELSE IF I-I, GO TO PLACE ELSE LET S=F.DATA
FOR J= 1 TO 1-2, LET S= S.DATA(S)
'PLACE' LET VALUE(S)= A
RETURN END

4-17 MONITORED ATTRIBUTES AND V,:RIABLES

Thus far, program names representiag data values have had either
memory locations or programs associated with them. Names defined as
variables referred to values stored in computer words; names defined
as functions referred to values computed or stored by associated
programs.
A new data type, a monitored variable, has both a storage loca-
tion and a program associated with it. The statements required to
define and use monitored variables parallel the statements required
to define variables and functions and to implement left-handed functions.
A variable (or array or attribute) is defined as monitored by a
statement of the form:

(a) DEFINE name AS A VARIABLE MONITORED ON THE LEFT or


(b) DEFINE name AS A VARIABLE MONITORED ON THE RIGHT or
(c) DEFINE nome AS A VARIABLE MONITORED ON THE RIGHT
AND T!,E LEFT
The word THE before RIGHT and LEFT is optional.
Since monitored variables have data values as well as programs
associated with them, mode and dimensionality declarations can also
be included, as in
DEFINE X AS A REAL, 2-DIMENSIONAL ARRAY MONIFORED
ON LEFT AND RIGHT
Monitoring on the right and on the left is ob d through programs
I
-263-

similar to righr- and left-handed functions. If a variable is declared


as monitored on the right (or left), a right-handed (or left-handed)
monitoring routine must be provided. A routine is able to perform a
monitoring function by the inclusion of one executable statement.
The statement differs, depending upon whether the routine is right-
or left-handed.
The task of a right-handed routine is to return a data value to
a calling program. A typical right-handed routine (not performing a
monitoring task) looks like:

ROUTINE EAPLE(I,J)

statements using I and J

RETURN WITH expression


END

The routine name (EXAMPLE) represents a program name, the argument


list transmits initial values for I and J from a calling program to
EXAMPLE, and the RETURN WITH statement returns a computed value to a
calling program.
Used for monitoring, a routine name represent~s both date and
program. EXAMPLE(K,5) is both a legitimate subscripted variable and
a call on a routine with arguments K aid 5. The additional statement
needed to convert a "regular" righE-handed routine to a right-handed
monitoring routine fetches a data value as.,ociated with a variable
and makes it accessible to a routine. The statement is

MOVE TO wuiable

Th? program

ROUTINE EXAMPLE(I.J)
MOVE TO Q

statements using I, J, and Q

RETURN WITH expreasion


END
-264-

starts out by assigning the value of EXAMFLE(I,J) to Q, which then


can be used freely in the routine. The MOVE statement variable can
be local or global, unsubscripted or subscripted, an attribute, or
ever. a left-handed function.
Except for defining EXAMPLE as being monitored, no other change
is made in the rest of the program. EXAMPLE is reserved and used
regularly; all data references are to EXAMPLE(I,J), as though it were
a simple subscripted variable.
Used for left-handed monitoring, the MOVE st.tement must assign
a value 'o the data cell associated with a monitored variable. The
statement that does this is of the form

MOVE FROM arithmetic expression

The value of the arithmetic expression is store- in the variable


referenced by the routine name and its arguments, if any, e.g.,
EXAMPLE(I,J). The form of a typical left-hand monitoring routine is

LEFT ROUTINE EAAMPLE(I,J)


ENTER WITH Q

statements using IJQ

MOVE FROM expression


RETURN
END
A value is transmitted to the routine by the ENTER statement, compu-
tations are performed, and a value is assigned to the monitored vari-
able by the MOVE statement.
The following short programs use monitored variables in several
different ways.
(I) Monitored variables used for data editing, where the monitored
variable feature provides two important benefita: (a) it keeps the
operational prograu clear of data checking and message printing state-
ments, making it easier to understand, and (b) ronversior of the pro-
gram to remove the editing feature can be accomplished by changing
I -265-

only one preambie card and throwing away two routines; the operational
program is unchanged. However, the program must be recompiled.

PREA14BLE
DEFINE DATA AS A REAL,2-DIMENS.OIWAL ARRAY
MONITORED ON THE RIGHT AND THE LEFT
NORMALLYMODE IS INTEGER
DEFINE MAND N AS VARIABLES
END
MAIN
READ NM RESERVE DATA AS N BY M
UNTIL MODE IS ALPWA,
READ I,J, DATA(IJ)
FOR 1-1 TO N. FOR J-1 TO M, DO
IF DATA(IJ)-O
IF J > I, LEI DATA (IJ) 1
GO TO L
ELSE LET DATA(1,J) . -1
ELSE
'L' LOOP
SKIP 1 FIELD ''THE ALPHA FLAG''
UNTIL MODE IS ALPHA. DO
READ I,J
PRINT 1 LINE WITH IJ, DATA(I,J) LIKE THIS
THE VALUE OF DATA(**,**) IS ******
LOOP
srop
END
ROUTINE FOR DATA(LK)
DEFINE VALUE AS A REAL VARIABLE
" THE FETCHING OF DACA(L,K) IS
"INHIBITED UNTIL THE SUBSCRIPTS ARE
" VERIFIED
IF L < 0 OR L > N OR K < 0 OR K > M, STOP
OTHERW'ISE...
MOVE TO VALUE ''THE VALUE OF DATA(L,K) IS FETCHED
RETURN WITH VALUE
END

LEFT ROUTINE FOR DATA(LK)


DEFINE VALUE AS A REAL VARIABLE
ENTER WITH VALUE
IF L < 0 OR L > N OR K < 0 OR K - M.
RTURN ''DON' T CHANGE THE VALUE
"OF DATA(LK) IF SUBSCRIPTS
O'ARE OUT OF BOUNDS )
OTHE RWI E...
MOVE FROM VAI.. ''TO DATA(L.K)
RETURN
END
-266-

(2) Monitored variables used for data transformations.

PREAMBLE
TEiPORARY ENTT!IIES
EVERY SAMPLE HAS AN XVAL AND A YVAL AND
BELONGS TO A GRAPH
PERMANENT ENTITIES
EVERY SERIES OWNS A GRAPH
DEFINE XVAL AND YVAI AS REAL VARIABLES
MONITORED ON rHE RIGHT
DEFINE GRAPH AS A SET RANKED BY HIGH YVAL WITHOUT
N ATTRIBUTE, WITHOUT FB.FAFL AND RS ROUTINES
NORMALLY. MOVE IS INTEGER
END
MAIN
READ N.SERIES CREATE EVERY SERIES
FOR EACH SERIES, DO
READ N
ALSO FOR I, 1 TO N.DO
CREA-E A SAMPLE
READ XVAL AND YVAL
FILE SAMPLE IN GRAPH
LOOP
FOR EACH SERIES, NOW PLOT.GRAPH
STOP
END

ROUTINE TO PLOT.GRAPH
" ASSUME XVAL BETWEEN 0 AND 132
" ASSUME YVAL BETWEEN 0 AND LINES.V-4
START NEW PAGE
PRINT i LINE WITH SERIES AS FOLLOWS
PLOT OF SERIES NUMBER **
FOR EACH I IN GRAPH, COMPUTE X AS THE MAXIMUM OF XVAL(I)
PRINT 2 LINES WITH XYVAL(F.GRAPH) THUS
X RANGE IS 0 TO '".
Y RANGE IS 0 TO "
SKIP 1 OUTPUT LINE
FOR EACH I IN GRAPH, DO
IF I - F.GRAPH. GO TO 'W' ELSE
SKIP TRUNC.F(YVAL(I)) - TRUNC.F(YVAL(P.GRAPH(1))) OUTPJT LINES
'W' WRITE AS B TRUNC.F(XVAL(I)) + ',I
LOOP
RETURN
END
-267-

" MONITOR ROUTINES CONVERT DATA VALUES


" BEFORE THEY ARE PLOTTED.CONVERSION IS
"OUTSIDE THE PLOTTING ROUTINE
ROUTINE FOR XVAL(I)
DEFINE V AS A REAL. VARIABLE
MOVE TO V
RETURN WITH LOG.E.F.(V) " FOR EXAMPLE
END

ROUTINE FOR YVAL(I)


DEFINE V AS A REAL VARIABLE
MOVE TO V
RETURN WITH V**2 " FOR EXAMPLE
END

The monitoring routines deliver transformed values of attributej


to the plotting routie witout changing their values in memory. As
there 4re no left-handed monitoring routines, XVAL and YVAL are stored
as they are read. To change the transformations, one need only change
the monitoring routines; MAIN and PLOT.GRAPH stay the same.

S4-28 SUBP.h9GRAM--A YEW VARIABLE TYPE

A variable declared as SUBPROGRAM by a statement of the form

DEFINE vaiabZt list AS A SUBPROGRAM VARIABLE

hai as its value the address of a routine. A--. assignment such as

LET A = 'SIN.J'

vhere X is a SLUPP0&zRAM variable, stores the couputer #ddrans of a


-outine (SIN.F in this case) in a vareable. The computer address can
be thought of as the name of the routine. SUBPROiGR/. varlazl!-. serve
the purpose of allow'ig routints to be called Ilnirecti'., rather than
explicitly.
A "-. ".. of the form '-.gw' to formi ty en, .- a

in singo. quotes4 the u~. of an- routine rase' as a procedKure or rig.ht-


handed functioii, either present in thc 5I$SCRIT II library or .vf1:,A
vithin a projram. A subprogram literal can be used to &ý4*41gn a ro!tine1

now to a SUJP•.hjPAM variable In an assignrwnt stat~-,.* or ci-,r'o,&h

Ex,:ept for in-lino functi~ns (see Table Z-,).


-268-

an argument list, or can be used as a test constant in a logical ex-


pression. Examples (a), (b), and (c) illustrate each of these uses.

DEFINE RTN AS A SUBPROGRAM VARIABLE

(a) LET RTN - 'DATA.TRANSFORM'

(b) CALL PROGRAM ('DATA.TRANSFORM')


ROUTINE PROGRAM (RTN)
DEFINE RTN AS A SUBPROGRAM VARIABLE

CALL RTN(Y) YIELDING X

RETURN WITH X**3


END
(c) IF RTN = 'DATA.TRANSFORM', GO TO Ll ELSE

SUBPROGRAM variables can be used rather than actual routine names


in procedure calls. When a SUBPROGRAM variable appears in a call state-
ment, the routine name stored in the variable is used in the routine
call.
One must be careful to distinguish between the direct and indirect
use of a SUBPROGRAM variable, however. If X is defined as a SUBPkOGRAM
array in a statement such as:

DEFINE X AS A !-DIMENSIONAL, SUBPROGRAM ARRAY

the statement

(a) RESERVE X(*) AS 10

allocates 10 data words to X itself; the statement

(b) RELEASE X

releases the space allocated to X; but the statement

(c) RELEASE X(7)

releases the routine whose name is stored in X(7). When all the ele-
ments of X are referred to, as in (a) and (b), X itself is the object
of a statement. When a particular element of X is mentioned, as in
(c), an indirect routine reference is implied.
-269-

If X is a right-hand monitored, 2-dimensional array, two steps


are needed to release both the array and its monitoring routine.

RELEASE X releases the array X(*,*)


LET Y= 'X' stores the "name" of the monitoring routine for X
in the SUBPROGRAM variable Y
RELEASE Y releases the routine named X

It is not possible to release a left-handed routine.


SUBPROGRAM variables can be global or local, SAVED or RECURSIVE,
subscripted or unsubscripted. They are initialized to zero when a
program begins execution or routines containing them (as RECURSIVE
variables) are called. Routines called indirectly through SUBPROGRAM
variables do not have their arguments checked during compilation --

the clauses

GIVING i A'GUME.,S and


YIFLD!'• i VALUES
cannot be used to ensure :hat argument conventions are being obeyed.
SUBPROGRAM varialles can also be used to call functions indi-
rectly. To do this, the following is required:
(1) The SUBPROGRAM variable must be declared to be INTEGER, REAL
or ALPHA mode in a statement of the form

DEFINE variable list AS A mode SUBPROGRAM VARIABLE

All functions called indirectly thrcdgh this variable must be of


the declared mode. If no mode is declared the current background mode
is assumed.
(2) An indirect function call is indicated by putting a dollar
sign ($) before a SUBFROGRAM variable name. If F is a SUBPROGRAM
variable, LET X = F assigns the name of a routine to the variable X,
while LET X = $F computes a value by calling on a function whose namne
is stored in F and stores it in X.
As with routines used as procedures, when a subscript list followo
a SUBPROGRAM variable it applies to the function called ndirectly,
and not to the SUBPROGRAM variable itself. SUBPROGRAM arrays can be
defined and routine names can be stored in them but they cannot be
used to cali upon routines. I
-270-

Several examples illustrate the definition and use of SUBPROGRAM


variables:
(1) Use of SUBPROGRAM variables as right-handed functions.

PREAMBLE
DEFINE FUNCTION AS A REAL, SUBPROGRAM VARIABLE
DEFINE K AS AN INTEGER VARIABLE
DEFINE X AS A 1-DIMENSIONAL ARRAY
END
MAIN
READ N RESERVE X(*) AS N
READ X
LET FUNCTION -'EXP.F1
'COMPUTE' FOR I= 1 TC N, COMPUTE S AS THE SLIM,
M AS THE MEAN AND V AS THE VARIANCE
OF iFUNCTION(X(I))
PR!NT 2 LINES WITH S, M AND V THUS
SUM- **.* MEAN= *.*
VARIANCE= *.**
IF FUNCTION: 'EXP.F',
LET FUNCTION- 'SQRT.F'
GO COMPUTE
ELSE
IF FUNCTION- 'SQRT.F'.
LET FUNCT:ON= 'LCG.2G.'
GO COMPUTE
ELSE
STOP END

(2) A different version of (.).

PREAMBLE
DEFINE FUNCTION AS A REAL, SUJBPROGRAM VARIABLE
DEFINE N AS AN INTEGER VARIABLE
DEFINE X AS A 1-biMENSIONAL ARRAY
END

MAIN
READ N RESERVE X(*) AS N
READ X
CAlL PPOCFSS DATA GIVEN 'EXP.-'
CALL PROCESS.DATA GIVEN 'SQRT.F'
CALL PROCESS.DPTA GIVEN 'LOM.,O.F'
STOP
END
-271-

ROUTINE TO PROCESS.DATA(J)
DEFINE J AS A SUBPROGRAM VARIABLE
DEFINE I AS AN INTEGER VARIABLE
FOR I - 1 TO N. COMPUTE S AS THE SUM,
MAS THE MEAN AND V AS THE VARIANCE
OF $J(x(1))
PRINT 2 LINES WITH S, MAND V THUS
SUM- **.* MEAN- **
VARIANCE- *.*
RETURN
END
(3) SUBPROGRAM mode variable used for program c-"itrol.

PREAMBLE
DEFINE ROUTER AS A SUBPROGRAM VARIABLE
DEFINE DATA AS A REAL, 1-DIMENSIONAL ARRAY
DEFINE STOCK AND BORROW.BIN AS VARIABLES
END
MAIN
RESERVE DATA(*) AS 3
LET ROUTER- 'INPUT'
'A' CALL ROUTER
LIST DATA, STOCK, BORROW.BIN
IF ROUTER = 0, STOP
ELSE GO TO A
END
ROUTINE INPUT
READ DATA
iF DATA(1) = 0 LET ROUTER= 'RECEIPT'
ELSE LET ROUTER= 'SHIPMENT'
RETURN
END
ROUTINE RECEIPT
ADD DATA(2)-1 TO STOCK
ADD 1 TO BORROW.BIN
LET ROUTER= 'INPUT'
kLTURN
END
ROUTINE SHIPMENT
IF DATA(2) < STOCK,
SUBTRACT-hATA(2) FROM STOCK
PERFORM SHIPPING.NOTICE
LET ROUTER- 'INPUT'
RETURN
ELSE LET ROUTER. 'BORROW'
RETURN
END
-272-

ROUTINE SHIPPING.NOTICE
PRINT 1 LINE WITH DATA(2), DATA(3) THUS
SHIP *** UNITS TO CUSTOMER ****
RETURN
END
ROUTINE TO BORROW
LET DIFF = DATA(2) - STOCK
IF DIFF < BORROW.BIN,
ADD DTFF TO STOCK
SUBTRACT DIFF FROM BORROW.BiN
LET ROUTER= 'SHIPMENT'
RETURN
ELSE PRINT I LINE WITH DATA(3) THUS
CAN NOT FILL ORDER FOR CUSTOMER *
IF DATA(3) > 10,0
LET ROUTER= 0
RETURN
OTHERWISE
LET ROUTER= 'INPUT'
RETURN
END

4-19 TEXT--A NLW MODE

The TEXT mode is declared for either attributes, variables, or


functions by the usual statements
NORMALLY, MODE IS TEXT or
DEFINE naw. AS A TEXT VARIABLE
TEXT variables store character strings of arbitrary length through a
dictionary (symbol table) mechanism. Character strings are stored in
sets, the "value" of a TEXT variable being a pointer to a particular
string. Several TEXT variables with the same value, i.e., with the
same character string assigned to them, have the same pointer vdle.
A character string is only stored once. Once stored, subsequent
attempts to store Identical strings only retrieve existing pointer
values.
A character string can be entered into a program in four ways:
The stacement
READ :'ari/,3tZ list
-273-

where variable has been declared as TEXT, reads a Word (defined in


the footnote on p. 120) in free-form. If X and Y are TEXT, the state-
ment READ X AND Y when reading the following data card

column number
00000000011111111112222222222333
12345678901234567890123456789012
ANTIDISESTABLISHMENTARIANISM IS

assigns the string ANTIOISESTABLISHMENTARIANISM to X and the string


IS to Y.
The statement

READ variable AS T e

illustrates a format for inputting TEXT data. 1he arithmetic expres-


sion associated with a TEXT variable must, of course, be positive.
If, in performing a formatted TEXT read, the end of a data card is
encountered before e characters have been read, a new card is read
and reading of the character string continues. The statement

READ TEXT.VAR AS B 1, T 400

defines an input character string of 400 characters. All characters


encountered in a formatted TEXT read are considered part of the text.
The statement

INPUT text list

uses a special delimiting character to mark off successive TEXT varn-


ablea in a free-form style statement. The Jelimiting character is
stored in the ALPHA global ariable MARK.V, which has a default value
of "". MARK.V may be changed when necessary. A text Ziat is a list
of TEXT variable names and /, B,and S formats. The statement

INPUT X,/,Y,S 10, Z

starts reading at whatever celumn the current input pointer is posi-


tioned; reads all the characters up to the first asterisk as the char-
acter string value of X; skips to a new card; reads all the characters
up to the first asterisk as the character string value of Y; skips
over the next 10 columns and reads all the characters up to the next
-274-

asterisk as the character string value of Z. The delimiting character,


* in this cas,,. not become part of the input character string.
A character string can also be entered into the dictionary as a
TEXT literal, specified as Icharacter str•ngi. Within a TEXT literal
a parallel (1) is represented by an underscore (_).
TEXT variables can be used in several ways: they can be corncat-
enated (linked together), compared, erased, or displayed.
The system function CONCAT.F(A,B) adds the character string
pointed to by the TEXT variable B to the character stuing pointed to
by the TEXT variable A. A new character string is formed; A and B
remain. For example, if A- ISIMSCRIPT. and B= 1III, -_ne statement

LET C- CONCAT.F(A&B) sets C- ISIMSCRIPTJII[.


Comparisons are made possible by considering all arithmetical
and relational operations performed with TEXT variables and functions
as INTEGER mode. Thus, if V1 and V2 are TEXT mode variables or func-
tions, the logical expressions VI = V2, VI NE V2, V2 = Icharacter
8tringf, etc., are true or false depending upon whether the variables
(functions) have the same pointer values. For example, if V1
ISPORTS.CARI and V2 z JSPORTS.j the logical expression V1 = V2 is
false. The logical expression V1 = CONCAT.F(VI, ICARI), however, is
true. The comparison VI > V2 is meaningless, as it expresses an
algebraic relation between two pointer values.
Statements of the form

LET text variable - Icharacter stringj


do either of two things: if the indicated character string is not
already in the dictionary, it im placed in it and a pointer to the
string stored in the text variable; if the literal string is already
in the dictionary, the existing pointer is used.
Cha,•acter strings pointed tu by TEXT variables are destroyed by
statements of the form

ERASE pointer list

The entire dictionary can be erased by the statement

FOR EACH V IN THE DICTIONARY, ERASE V


-275-

Since more than one TEXT variable can point to the same text data,
the ERASE statement must be used with care. The following few state-
ments show why care is necessary.

DEFINE NAME AND LABEL AS TEXT VARIABLES


READ NAME AS /,T 50
LET LABEL - NAME

ERASE NAME

The text pointed to by LABEL no longer exists. The FOR phrase

FOR EACH variable IN THE DICTIONARY,

can be used like any other FOR phrase to control a program's operat~o~s.
Each TEXT variable has an INTEGER attribute whose value is Zhe
number of characters contained in the variable. Each declaration

DEFINE none AS A TEXT VARIABLE


defines an attribute LENGTH.A(nme). To illustrate: LET NAME=
IJOHNSMITHI sets the TEXT variable NAME "equal to" the character
string IJOHNSMITHI. After execution of the LET statement, LENGTH.A
(NAME) equals 10.
TEXT values can be output by three different statemnts. State-
mento of the form

WRITE variable AS T e

write output on the current output unit, starting at the column ptinted
to by the current output pointer. More than one line is printed if
the expression e requires it.
Statements of the form

OUTPUT text list

comence writing at the current output pointer column, and continue


until the TEXT data stored in one or more variables are exhausted.
The formats 8,S,/. and * can be used in the text liar for editing.
And the statement

LIST ari able


-276-

displays the first 14 characters of a TEXT variable In the standard


LIST format. If a TEXT variable contains fewer than 14 characters,
the characters displayed are left-adjusted.
The INPUT, OUTPUT, READ, and WRITE statements can be followed
up by a USING clause when necessary.
Conversion between TEXT and other modes is provided by three
functions:

TTOA.F(pointer) converts the first four÷ characters of the


TEXT value pointed+ at to ALPHA.
ATOT.F(variable) converts the four' characters of the indi-
cated ALPHA variable to TEXT, storing them
in the dictionary, if necessary.
ITOA.F(expression) converts the first fourt digits of an
INTEGER expression to ALPHA.

Table 4-8 shows the functions provided by SIMSCRIPT II for con-


verting from one data mode to another.

Table 4-8

MODE CONVERSION FUNCTIONS

INTEGER REAL ALPHA TEXT

INTEGER -Automatic oz REAL.F ITOA.F

REAL INTJF or TRUNC.FI

ALPHA ---- ---- ATOTF

TEXT TTOA.F

The features of the TEXT mode are illustrated 4n the following


examples:
(1) This program reade a number of sentences, orders them accord-
ing to their length, and prints thetr out:

Assumina " 4A variable can hold four characters.


-277-

PREAMB1,E NORMALLY, MODE IS INTEGER


DEFINE SENTENCE AS A 1-DIMENSIONAL,
TEXT ARRAY
END

MAIN
READ N RESERVE SENTENCE(*) AS N
LET LET MARK.V= "."
FOR I= I TO N, INPUT SENTENCE(I)
'ANOTHER' FOR EACH I IN THE DICTIONARY,
COMPUTE MAX= THE MAXIMUM(1) OF LENGTH.A(1)
IF MAX= OSTOP
OTHERWISE
OUTPUT, SENTENCE (MAX)
ERASE SENTENCE (MAX)
GO TO ANOTHER
END

(2) This program reads a deck of name cards, in which names are
punched in the form first name bian.k last cine, and counts the number
of cccurrences of different names:

PREAMBLE
DEFINE FIRST AND LAST AS TEXT VARIABLES
NORMALLYMODE IS INTEGER
END

MAIN
'READ' IF DATA IS ENDED,
PRINT 1 LINE WITH JOHNGREGSMITH,HH THUS
COUNTS ARE *** *** *** **
STOP ELSE
READ FIRST AND LAST
IF FIRST EQUALS IJOHNI, ADD I TO JOHN
ELSE
IF FIRST EQUALS I GREGORY!. ADD I TO GREG
ELSE
IF LAST EQUALS 1SMITHj, ADD 1 TO SMITH
ELSE
IF CONCAT.F(FIRSTLAST)- 1 HORATIOHORNBLOWER!
ADO 1 TO HH
ELSE GO READ
END

(3) These program sozments are part of a large stmulation program:

PREAMBLE
TEMPORARY ENTITIES
EVERY JOB HAS A DESCRIPTION, A PRIORITY, A
DUE.CDATE AND MAY BELONG TO A QUEUE
-278-

DEFINE DESCRIPTION AS A 'EXT VARIABLE


DEFINE DUE.DATE AS A REAL VARIABLE

END

MAIN

" READ DATA FOR JOBS''


CREATE A JOB START NEW INPUT CAAD
READ DESCRIP IONPRIORITYDUE.DATE
AS T 50, I 10. 0 10.?

REMOVE THE FIRST JOB FROM IUE IIE(5)


LiST ATTRIBUTES OF J4B

END

(4) Three ways to do INTEGER to TEXT conversion:

I is 4n INTEGER variable
T is a TEXT variable

(a) WRITE I AS /. I 10, "-" USING THE BUFFER includes all


INPUT T !ISING THE BUFFER leading bldnks
(b) WRITE I AS /, 1 10 USING THE BUFFER starts reading
READ T USING THE BUFFER at the first non-
blank character

(cl LET T - ATOT.F(ITOA.F,8))


(5) U•. of TEXT for output oasagos.

koutine definition:

ROUTINE ERROR GIVEN T


DEFINE T AS A TEXT VARIABLE
WRITE T AS /, B 10, "TME ERROR IS', T 25
END
Routinea ue:
-279-

IF VALUE LIMIT, CALL ERROR(I FATALVALUE TOO HIGHI)


>
STOP
ELSE IF VALUE - LIM!T.CALL ERROR(1 RECOVERABLE,CONTINUINGI)
PERFORM RECUVERY
REGARDLESS

(6) Creating, using, and destrcving at. entity having a TEXl


attribute:

PREAMBLE
TEMPOPARY ENTITIES
EVERY MAN HAS A NAME,AN AGE AND A SALARY AND BELONGS
TO A GROUP
DEFINE NAME MND N AS TEXT VARIABLES
THE SYSTEM OWNS A GROUP•
END

MAIN
LET MARK.V-"
'BACK' READ N
IF N NE I DATA GROUP ENDED ,
CREATE A MAN
LET NAME - N
READ AGE AND SALARY
FILE THIS MAN IN GROUP
GO BACK
ELSE
START ,EW PAGE
PRINT 2 LINES WITH N.GROUP AS FOLLOWS
THIS GROUP CONTAINS "** PEOPLE
NAME AGE SALARY
FOR EACH MAN IN GROUPDO
REMOVE THE MAN FROM THE GROUP
WRITE NA.EAGE AND SALARY AS 9 15, T 25, 2 I 10
ERASE NAME
DESTROY MAN
LOOP
IF DATA IS ENDED, STOP
ELSE GO BACK
END

7-." A 'J ;,Y.'. W 7....


"-

At tions it in necessary to store REAL nt,"birs in INTE&ER


varir is. &nd INTEGEiR,
-.. ALPHA, TEXT, or SUIPROGWAM valuos in REAL
fari.-tbloe. when this it done, it is generally for 3•-m rurpose oul-
side the facilities of SI.'MCRI7T I1, e.g., c-m&nicat1lvn vith a

I
-280-

machine-language subprogram or performance of a rather exotic algo-


rithm. The STORE statement permits ary computable value to be
assigned without conversion. The form

STORE arithmetic expression IN variable

expresses a command to compute or retrieve a value and to assign it


to a stated location.

Table 4-9 reviews the forms a STORE statement can take.

Table 4-9

STORE STATEMENT COMPONENTS

Arithmetic Expression Variable

INTEGER expression Variable


data value
array pointer Attribute
identification number Left-handed function
INTEGER constant Monitored variable
REAL expression
REAL constant
ALPHA variable
"ALPHA literal"
TEXT variable
ITEXT literal'
SUBPROGRAM variable
'SUBPROGRAM literal'
-281-

Chapter 5

SIMSCRIPT I: LEVEL 5

5-00 INTRODUCTION
Unlike Levels 1 through 4, which present a rather general pro-
gramming language, Level 5 provides concepts and programming features
for a specific applications area, discrete-event simulation. Readers
unfamiliar with this subject are advised to read any one of a number
of current texts or P. J. Kiviat, Digital Computer Simulation:
Modeling Concepts, The RAND Corporation, RM-5378-PR, August 1967.
While some methodological comments are made in this section, it is
not intended as a text, and will most likely prove unsatisfactory to
persons unfamiliar with the subject. Readers who have done simula-
tions, and particularly those who have used a simulation programming
language, should haie no difficulty following the section without
additional preparation.
Simulation as we deal with it is the use of a numerical model
of a system to study its behavior as it operates over time. Dis rete-
event simulation deals with models whose entities interact with one
another at discrete points in time, rather than continuously. This
section presents concepts and statements designed to aid in modeling
systems and in programming them so that they can be simulated. Its
organization reflects subject areas that are Important to this task:

Sec. 5-01, DESCRIBING SYSTEM DYNAMICS


Sec. 5-02, CONTROLLING SYSTEM DYNAMICS
Sec. 5-031 MODELING STATISTTCAL PHENOMENA
Sec. 5-04, MODEL DEBUGGING AND ANALYSIS
-232-

5-01 DESCRIBING SYSTEM DYNAMICS

The basic unit of action in a SIMSCRIPT II simulation is an


activity. In a simulation of supermarket operations, we might find
such activities as: customer selecting merchandise, customer walking
to checkout counter, and customer checking out, among others that deal
with different aspects of supermarket operations. Two important facts
about activities are (1) that they take time, and (2) that they
(potentially) change the state of a system.
When cne constructs a simulation model he must provide a charac-
terization of system activities that enables the model, when operating,
to reproduce the time-dependent behavior of the system being simulated.
That is, he must construct the activities in such a way that, when
each occurs, the system state changes in the proper way. This imposes
requirements ior (1) correctly modeling the things that activities
do, and for (2) sequenciv3 the execution of subprograms that represent
activities, so that the order of performance of activities within a
model corresponds to the order in which the same activities occur in
the real system.
The concepts embodisd in Levels 1 through 4 are the stuff that
activity descriptions are made of. Systems are described (modeled)
in the language of entities, attributes, and sets.
Keeping track of simulated time and organizing subprograms that
represent system activitie's are the prlvary tasks of Level 5. The
cz.mtral concept employed is that of an event. An event is an instant
in time a& which an activity starts or stops. Usually, an activity
is bounded by two 3vents, as shown below:

1--- machining act ivitv---

start machining stop machining


event event
-- - driving activity-----.

scart driving stop dr~ving


event event

Typical activities
-283-

The time between events that represents the duration of an


activity is always modeled as a time-delay factor. Changes in a
system that take place when an activity starts or stop*, in the
instant of time when an activity begins or ends, are associated with
events rather than activities. This is the crucial difference between
discrete-event and continuous-time simulators. In discrete-event
simulation languages such as SIMSCRIPT II, state-changes take place
only at specified points in time at which inteiactions between system
entities occur. In continuous-time simulation languages, interactions
and state-changes take place continuously. To aodel continuous
changes, either analog computers or numerical integration procedures
must be employed.
Some activities have no duration and are modeled as single events.
These are activities such as the preparation of a report or a plan
that is issued periodically. Activities can be modeled as consuming
zero time if no system interactions occur during the activity time,
and the activity time is short.
To model an activity that takes some time to perform, one speci-
fies two events. In the first event, the necessary tests and state-
changes are made to put the actiity into operation and an instruction
is given to the SIMSCRIPT II system to schedule a second event to
occur aiter the passage of some units of simulated time. When this
time passes and the second event is called, it does what testing and
state-changing it must to terminate the activity. It may trigger one
or more subsequent events. The keys to understanding how the passage
of time is simulated are to understand (1) that events take place
instantaneously, (2) that events are modeled as SIMSCRIPT II sub-
programe that are executed in zero simulated time, and (3) that the
SINSCRIPT II system con~aine a special routine, called a t;'1-_'.g roul.f'e,
that accepts requests for the execution of events at specified future
times and organizes them so that the event routines are called in the
orser of their time scheduling. and hence in the order in vhirh they
should occur temporally. Tbh ttulng 'outlne also keeps track of simu-
lated system time with An artiflcla- system clock.
In Lhis section we limit ourselves to the definition of important
simulation concepts, such as:
-284-

activity
event
timing routine
simulation clock
event scheduling in simulated time
instantaneous charges of system state

and the presentation of statements that allow these conceots to be


defined within a SIMSCRIPT II program. Section 5-02 goes further
into how the timing routine works and how events are scheduled and
executed.
While it has not been pointed out explicitly why the normal main-
program-subprogram structure ie not adequate fir the simulation task,
it is not difficult to reason out why this is so. Consider the follow-
ing situation: a simulation model has one kind of entity, call it a
MAN, that performs one kind of activity, call it a JOB. Let the job
activity be delimited by to•e two events START.JOB and END.JOB. Let
two men somehow appear and be given jobs to perform, i.e., the simula-
tion must execute the routine START.JOB for each MAN. If the men
arrive at the same time these programs must be executed simultaneously,
i.e.. in parallel. On a sequential computer this is impossible, of
course. It is possible, howeveL,
to execute them szquentially without
+
occurred.
advancing the simulation clock after the first event has
If two events occur when the simulation clock has the same time, we
can think of them as happening simultaneously.
Now. within the event START.JOB the event END.JOB will be scheduled
to occur after some job performance delay time. When the event END.JOB
occurs for the first MAN, the simulation cicck will be advanced to
some higher value, i.e., it vill indicate that simulated time has
pa&sed. Therefore, when the first START.JOB has occurred it cannot
CALL its respective END.JO8 and advance the simulation clock because
the second START.JOB has nct yet been exe.:uted. Some statement other
then CALL is required to instruct the SiMCRZPT 1I system that END.JO8
is to be called after all events that have lower clock times associated
with them have been called.

Section $-,'? discusses techniques for handlinS complex time


interact ions.
-285-

In Fig. 5-1 two jobs are started and ended at different times
to illustrate the concepts of event occurrence and event scheduling.

Job, activity

-Job2 activit4

Simulated
time
START.JOB 1 END.JOB 1
START.JOB 2 END.JOB 2

Fig. 5-la -- Two overlapping activities

Job, activity

Job., activity

' ' Simulated


START.JOB END.J108 tim

START'JOB 2 END'4008 2

Fig. 5-lb -- Two nested activities


-286-

I .. I ,._

Simulated time
I II

START.JOB1 END.JOB1

START.JOB 2 END.JOB2

Fig. 5-ic -- Two activities with a common event time

Table 5-1 lists the order in which subprograms representing the


START.JOB and END.JOB events of Fig. 5-1 have to be executed.

Table 5-1

FIGURE 5-1 EVENT ORDER

Fig. 5-la Fig. 5-lb Fig. 5-1c

I START.JOB1 START.JOB1 [START.JOB1


Time I in parallel
START.JOB2 START.J082 \START.JOB2/

END.J08 1 END.JOB2 END.JOBI

END.JOB2 END.J08 1 .ND.J08 2

Two classes of events are possible in any simulation model: vvents


generated within the model and events fed to the model trom the outside
world. The former are called INTERNAL or ENDOGENOUS events, the latter
EXTERNAL or EXOGENOUS events. Each has a routine associated with it
that describes actions the simulated system takes when the event
occurs. The difference between the types t% t'as! INTERNAL events are
caused by the explicit reaction of a model to its operations -- the
-287-

model generates or "makes up" INTERNAL events as it progresses --

while EXTERNAL events are fed to a model from a data source (a mag-
netic tape or disk, or punched cards). Generally, EXTERNAL events
provide stimuli to a model and INTERNAL events react to them.

Event Declaration

A routine is declared to be an event rather than a callable sub-


program by use of the word EVENT or UPON rather than ROUTINE in its
first statement. Typical event declaration statement3 are:

EVENT ARRIVAL GIVEN LOCATION AND ALTITUDE


UPON DEPARTING(DESTINATION)
UPON LEAVING THIS PLACE
EVENT ALLOCATION(SUM, PERSON1, PERSON2)

These statements show that event declarations are similar to routine


declarations in that they can have input arguments and can use the
different input argument forms described in Sec. 2-19. Events cannot
have yielding arguments for the simple reason that they are not called
directly from subprograms and have no place to return output values.
The general form of an event declaration statement is:

EVENT name optional input argument list or


UPON name optional input argunent list

Events can be triggered either internally or externally. If they


are triggered internally it is by something called an event notice
(discussed in the following subsection); if they are triggered ex-
ternally it is by an externaZ event data cardi (discussed in Sec. 6-0:).
Since an event subprogram can occur in either of two ways, and each
of these ways provides a diffetent source of data for the event, a
logical expression is provided for use within an event in determining
how an event occurrence was triggered. The expression compares the
keyword EVENT with either of the property words INTERNAI or EXTERNAL
and yields a true or filse rpsult. The form of the expression is

EVENT IS ?,•r:i or
EVENT IS NOT 'rt

as in the statements
-288-

IF EVENT IS INTERNAL, GO TO INTERNAL.PROCESS ELSE and


IF EVENT IS EXTERNAL AND DATA IS ENDED, STOP OTHERWISE

Succeeding subsections contain eý-amples that make it clear why


this statement is necessary and how .t is used.

Internal Events

When an event is generated within a program, a message, called


an event notice, is used to carry information about the event from
the generating routine to the SIMSCRIPT II timing routine, and from
it to the event when its turn for execution comes about. An event
notice is very much like a temporary entity; in fact, it is a temporary
entity that has five special attributes. The first of these contains
the simulated time at which the event represented by the event notice
is to occur; the second contains an event type code that tells whether
an event occurred internally or externally; the third, fourth, and
fifth are attributes for the set the timing routine uses to keep track
of scheduled events. These attributes are called TIMF.A, EUNIT.A,
P.EV.S, S.EV.S, and M.EV.S, respectively. The timing set is sub-
scripted and named EV.S.
Event notices can have attributes that are either variables or
functions, and can own and belong to sets. EVERY statements art used
to declare them.
The statement

EVENT NOTICES

placed before a group of EVERY statemntj notlfies the compiler that


event notices rather than temporary or permanent entity declarations
follow. The compiler places the special attributes in the first five
words of each event notice record; the programmer does not have to
rnma them. He must be careful not to place attributes of his own in
these first five words.
Often, event notices only have the special attributes and no
additional attributes or set pointers. Tley are used to trigger
events, not to carry information to them. When this is the case.
the phrase
-289-

INCLUDE event notice name list

is added to the EVENT NOTICES statement to notify the compiler that


these event notices exist and five-wcrd event notice records have to
be defined for them. A typical simulation program preamble might
start off like this:

PREAMBLE
EVENT NOTICES INCLUDE ARRIVAL, WEEKLY.REPORr AND END.SIm
EVERY JOB.OVER HAS A NEXT.JOB AND OWNS SOME RESOURCES
When created, records for these event notices look like

ARRIVAL WEEKLY.REPORT END.SIM JOB.OVER

word I TIME.A TIME.A TIME.A TIME.A


word 2 EUNIT.A EUNIT.A EUNIT.A EUNIT.P
word 3 P.LV.S P.EV.S P.EV.S P.EV.S
word 4 S.EV.S S.EV.S S.EV.S S.EV.S
word 5 M.EV.S M.EV.S M.EV.S M.EV.S
NEXT.JOB
F.RESOURCES
L.RESOURCES
N.RESOURCES

Section 5-0-2 describes how event notices are created and ,•sed.
It is sufficient at this poiit that the reader understand rt at they
are created and destroyed like temporary entities, and uied by the
SISCRIPT II timing routine to organize the execution of events in
proper time sequence.
The reader bhould also understand at this point that it it pos-
sible to have many e¢ents of the saga kind scheduled to occur at thm
saw* or different times in the future. 'or esmpl*, a machine-shop
,imulation having an zvvnt END.J0" that signals th,ý completion of a
machining operation and cdarges the state of the simulated systct

vhf.a job is completed, can have many EN4.JOB events sche'uled and
held in abeyance by the timing routine. Thnese events are usually
scheduled to take plac- at differe-r times, and the ttiing routine
-290-

is able to organize them, by ranking them on their scheduled occur-


rence times so that the events with the earliest (smallest) event time
are selected first. If two events of the same kind happen to have
the same event time, the timing routine uses a first-4chedut.ed, first-
occurs rule to "break the tie." The order in which events are executed
is determined by the order in which they are scheduled. While several
events can take place at the sam instant in simulated time (the
simulation clock ha. the same value during each event) there are
often good reasons for wanting to give priority to one event notire
or other. The BREAK TIES statement accomplishes this.
A statement of the form

BREAK event name TIES BY HIGH attribute 'a1wn' or


BREAK event name TIES BY LOW attribute name

gives priority to the event with the high (low) attribute value when
two or more event notices of the same type have the sae event time.
The attcibutes are, of course, ones that have been defined in EVERY
statements for the event named. In cases where more than one set of
tie-breaking attributes are needed, clauses of the form

* THEN BY HIGH attribute naoe or


* THEN BY LOW attribute now

can be added to the BREAK TIES statement. As many may be added as


are necessary.
Events defined by the statements

EVENT NOTICES
EVERY ARRIVAL HAS A VALUE, A DUE.DATE AND A PRIORITY

can n-ave ties resolved among competing event notices by statements


such as

(a) BREAK ARRIVAL TIES BY HIGH PRIORITY


(b) BREAK ARRIVAL TIES BY HIGH PRIORITY, THEN BY LOW MJE.DATE
(c) BREAK ARRIVAL TIES BY HIGH VALUE. THEN BY LOW PRIORITY.
THEN BY HIGH DVE.DATE

In (a), among ARRIVAL event notice* scheduled to occur at the


same simulated time, the event notice vith the largest PRIORITY sttri-
bute will occur first. in (b), among event notices scheduled to occur
-291-

at the samw simulated time and having identicalc PRIORITY values, the
notice with the smallest DUE.DATE vill occur first. And similarly
for (c) and other variations.
Conflicts between different kinds of events are of similar impor-
tance. It often happens that several different events are scheduled
for the same time, as for example, the arrival of a job, the comple-
tion of a task, and the preparation of a management report. Resolviag
these conflicts is Important in situations where events compete for
the same resources or have som effect upon one another. A statement
of the form

PRIORITY ORDER IS event name lit

places an cidering upon the events named so that in cases where event
notices of different kinds have the same event time, the event notice
of the higher-priority event type is selected first. Priority in
this case corresponds to position in the PRIORITY statement; the first
event named is given the highest priority. If no PRIORITY statement
appears in a program, events are given priority in the order in which
they appear in the preamble, in either INCLUDE or EVERY statements.
If only a subset of the events of a program are listed in a PRIORITY
statement, the remaining events are given lower priority than the
ones listed, and are ranked among themselves in the order in wh!ch
they appear.
The folloving preamble illustrates the use of BREAK TIES and
PRIORITY statements in a typical simulation program:

PREAMBLE
EVENT NOTICES INCLUDE END.OF.JOS AND SHIFT.CHANGES
EVERY CAR.ARRIVAL HAS A VALUE AND AN IDENTITY
EVERY TRUCK.ARRIVAL HAS A LOAD.WEIGHT AND A DENSITY
EVERY START.J06 HAS A VEHICLE AND A CREWSIZE
BREAK CAR.ARRIVAL TIES BY HIGH VALUE
BREAK TRUCK.ARRIVAL TIES BY LOW DENSITY, THEN BY HIGH LOAD.WEIGHT
BREAK START.JOB TIES BY LOi CREWSIZE
PRIORITY ORDER IS TRUCK.ARRIVAL, CAR.ARRIVAL, START.JOB, END.OF.JOP,
SH I FT. CHANGE S
DEFINE IDENTITY. LOAD.W[EGHT, AND CREWSIZE AS INTEGER VARIABLES
DEFINE VEHICLE AS AN ALPHA YARIABLE
END
-292-.

External Events

Events can be triggered from outside a simulation model by de-


claring them to be EXTERNAL EVENTS. Some events are triggered only
externally. Other events are triggered only internally; for them,
only EVENT NOTICES declarations are used. Some events are triggered
in both ways. We have described how event notices are defined and
left the discussion of how they are used to the next section; we do
the same for external events, describing now how they are defined and
leaving the discussion of how they are used to Sec. 5-02.
An event is defined as having an external trigger by using its
name in a statement of the form:

EXTERNAL EVENTS ARE event nane list

When an event name appears in an EXTERNAL EVENT statement and is


not declared as an event notice, provision is made to create a five-
attribute event notice, named event, each time a data card containing
the event name appears on en externai event unit. The event notice
is of the form:

word 1 TIME.A
word 2 EUNIr.A
word 3 P.EV.S
word 4 S.EV.S
word 5 M.EV.S

The first, third, fourth, and fifth attributes have the same
meaning as in the preceding subsection; the second attribute contains
the numuer of the input unit on which information about the event is
contained. External event input units are c'lfined in a statement of
the form:

EXTERNAL EVENT UNITS ARE device name list

In this statement, device names can be given as integer constants or


as variables. If variables are used, they must be initialized to
device name values before the start of simulation. If no EXTERNAL
EVENT UNITS statement appears, the standard input unit is assumed to
-293-

be a source of external event data. If several input devices are


used, the standard input unit must be listed with them if it is to
be a source of external events.
A simulation program having the events ARRIVAL and REPORT might
contain the following statements in its preamble:

EXTERNAL EVENTS ARE ARRIVAL AND REPORT


EXTERNAL EVENT UNITS ARE DAILY.ARRIVALS, WEEKLY.ARRIVALS,
AND 5

These statements indicate that the SIMSCRIPT II system must be prepared


to execute the events ARRIVAL and REPORT as external events, and that
three input devices are to be used to input external event triggers.
The programmer indicates mnemonically that he intends to put informa-
tion about arrivals that occur daily on one input device and informa-
tion about arrivals that occur weekly on another. The SIMSCRIPT II
system attaches no significance to the names; it merely knows that
three input devices are to be used.
Events that are only triggered externally can be given tie-breaking
priority over other external events and over internally generated events
by putting their names in a PRIORITY statement. Using the above state-
ments as an example, the statement

PRIORITY ORDER IS REPORT AND ARRIVAL

states that if simultaneous events come up on the multiple event units,


REPORT events are to be executed before ARRIVAL events. It is not
possible to attach priorities to external event unita, e.g., service
DAILY.ARRIVALS befcre WEEKLY.ARRIVALS. Only events may be given

priorities.
Events that occur both internally and externally can be give"
priority over other kinds of events but cannot be ranked among them-
selves by a BREAK TIES statement. As only the internally generated
event notices have ranking attributes, the externally triggered event
notices compete with them on a first-come, first-served basis.

5-02 CONTROLLING SYSTEM DYNAMICS

Three things must be understood about system dynamics: how the


-294-

SIMSCRIPT II timing routine organizes events so that they are executed


properly in simulated time; how internal events are scheduled; and how
external event data are prepared and input. The first three parts of
this section address these issues.

The Timing Routine

Every simulation program contains the statement

START SIMULATION

which instructs the SIMSCRIPT II operating system to start taking


instructions from the simulation timing mechanism. For there to be
something to do at the start of simulation, a programmer must initialize
the system state and provide initializing events that set the system
in motion. A typical simulation main program is organized as:

MAIN
Iocal declarations
initialization of entities, attributes
and sets
initialization of events
specification of external event units
START SIMULATION
control statements
END

When the timing mechanism finds nothing to do, i.e., no events


are scheduled, control passes to the statement after START SIMULATION.
As long as events are being executed, the timing routine, represented
in the main program by the START SIMULATION statement, is in control.
One way to end a simulation is to cease scheduling future events and
let the timing mechanism automatically branch beyond the START SIMULATION
statement when all currently scheduled events are completed.
The heart of the liming routine is a singly subacripted set in
which event notices are filed. Each subscript value denotes a dif-
ferent event class; in a simulation with six different event classes
there are six different sets. The global variabie EVENTS.V has as
its value the number of event classes. The timing routine set is
named EV.S, which stands for "events set"; it has the attributes
F, P, S, and M and the routines RS and RF are defined. Internal
-295-

events with BREAK TIES conditions are put into their proper sets by
routines named C.event; internal events not named in BREAK TIES state-
ments, and external events, are put into their sets by a routine named
A.EV.S, which is the standard FILE routine for the set EV.S.
Each event has a global variable I.event associated with it that
denotes the subscript value of the event class in the subscripted
events set. In a program without a PRIORITY statement, values are
assigned to these variables in ascending order as event names appear.
When a PRIORITY statement is used, values are assigned in the order
in which events appear in the statement. An example illustrates these
points:

Preamble:

PREAMBLE NORMALLY MODE IS INTEGER


EXTERNAL EVENTS ARE ARRIVAL AND STOP.SIMULATION
EVENT NOTICES INCLUDE ARRIVAL, END.OF.JOB AND SHIFT.CHANGE
EVERY START.JOB HAS A VALUE, A DUE.DATE AND A
PROCESS.TIME AND BELONGS TO A ROUTING.SET
PERMANENT ENTITIES....
EVERY MACHINE HAS A CAPACITY AND A RATE AND OWNS A
WAITING.LINE
TEMPCRARY ENTITIES....
EVERY JOB HAS A TIME.WANTED, OWNS A ROUTING.SET AND
BELONGS TO A WAITING.LINE
PRIORITY ORDER IS STOP.SIMULATION, SHIFT.CHANGE, END.OF.JOB,
START.JOB AND ARRIVAL
BREAK START.JOB TIES BY LOW DUE.DATE, THON BY HIGH VALUE
END
Meaning:
Five events are defined: ARRIVAL, STOP.SIMULATION, END.OF.JOB,
SHIFT.CHANGE, and START.JOB: EVENTS.V-5. The subscripted set EV.S
therefore has five subscript values. These values are specified by
the order of the events in the PRIORITY statement and are:
I.STOP.SIMULATION-1, I.SHIFT.CHANGE-2, I.END.OF.JOB-3, I.START.JOB-4,
and I.ARRIVAL-5.
The subscripted variable F.EV.5 has five elementg, one for each
event class. Each event notice has five attributes, TIME.A, EUNIT.A,
P.EV.S, S.EV.S and M.EV.S; START.JOB has six additional attributes.
The routines A.EV.S, X.EV.S, and Z.EV.S are generated to file
events not mention:d in BREAK TIES statements in their ;roper sets

Ir._ _
-296-

and remove the first event or a specific event from a set, The routine
C.START.JOB is generated to file event notices in EV.S (I.START.JOB)
according to the rankings specified in the BREAK TIES statement.
Simulation event control is maintained in the following way:
(a) Every time an internal or external event is scheduled it is
filed in its proper set. Events are filed in their set* in the order
in which they are to be executed, i.e., the event with the smallest
event time is filed first.
(b) When control returns to the timing mechanism from an event,
or from the main progr.am, the next event to be performed is selected
by taking the event with the smallest event time "rom its set. This
is done by searching the event sets in the order specified by their
I.event variables, and keeping the identification of the event notice
with the smallest event time. By doing this, two events of the same
class will have their tie resolved by the ranking within the set, and
two events of different classes with the same event time will have
their tie resolved by keeping the identification of the first one
found.
Figure 5-2 pictures the way the events of the above preamble are
organized. Normally, a programmer does not deal with the set EV.S
directly, or with the variables F.EV.S, P.EV.S, S.FV.S, M.EV.S. TIME.A,
and EUNIT.A. He inserts events into the event sets with soecial state-
ments and data inputs, and has them removed from the sets automatic-
ally. When an event is removed, its event time TIME.A is transferred
to the simulation clock TIME.v, becoming the updatet simulation time,
and control is transferred to the event routine.

Scheduling Internal Events

We have shc,%n how an event notice is taken fro? its event set by

the timing routine and used to initiate the execution of an event.


The details of how an event is executed once its notice is received
are discussed a little later in this section. Here we discuss how
an event notice for an internal event is filed in its appropriate
event set.
The statement
-297-

F EV, S Event sets are ordeed 'p


by PRIORITY or their
order of appearance
in the PREAMBLE

All sets are ordered


by BREAK TIES
specification or
time rankMing

0 0

STOP. SIMULAI LON


ARRIVAL

t.

--------- 4

7 It

Fig. 5-2 -- Timinq set Crganization


-298-

SCHEDULE AN event AT time expression

creates an event notice of class event , sets its TIME.A attribute to


the value of the time expression, and files the event notice in the
proper set for that event class. The words CAUSE and RESCHEDULE are
synonyms for SCHEDULE. Situations often exist where they are more
expressive of the task being performed. The event nottce is actually
a temporary entity. The statement specifies that a temporary entity
of a certain size be crested, with its identification number stored
in a global variable with the sam nme as the entity, and be used for
scheduling the future occurrence of an event of that class. The
statement is equivalent to a statement of the form:

SCHEDULE AN event CALLED event AT time expression

where event is the global variable associated with the entity class.
One can just as easily write a SCHEWLE statement with a different
variable nme, as in

SCHEDULE AN ARRIVAL CALLED RUSH.ORDER AT time exprvesion

If an event notice already exists (it may have been created pre-
viously), one can specify that it be used in a SCHEDULE statement by
using the word THIS rather than AN. as in

SCHEDULE THIS ARRIVAL AT time expression

This inhibits creation of a new entity. The identification number


of the event notice that is to be used is assmed to be stored in the
global variable ARRIVAL. The statement form

SCHEDULE THIS entity CALLED variable AT tims expression

says that an identification number of an event notice of the class


entity is stored in -azriz•be and is to be used in a scheduling statement.
Several variations of these statement formal are permitted. The
words A and AN are synonyms, as are the vords THIS. THE, and THE ABOVE.
Thus one can say:

(a) SCHEDULE AN ARRIVAL AT time ezrýrteiot


(b) SCHEDULE THE ABOVE ARRIVAL CALLED RM AT !;.n sxrr*en
,c) CAUSE THIS ARRIVAL AT e.m exreson
-299-

Statement (a) creates an event notice before scheduling; statements


(b) and (c) use event notices of type ARRIVAL, whose identlfication
numbers are stored in RUSH and ARRIVAL, respectively.
If an event notice has attributes, as in START.JOB delined on
p. 295, values can be assigned to them in two ways: through standard
attribute (entity) references in LET statements and through the SCHEDULE
statement itself. Reca]l that the event START.JOB was defined by the
statement

EVENT NOTICES....
EVERY START.JOB HAS A VALUE. A DUE.DATE AND A PROCESS.TIME
AND BELONGS TO A ROUTING.SET

This means that every START.JOB entity record looks like:

word 1 TIME.A
word 2 EUNIT.A
word 3 P.EV.S
word 4 S.EV.S
word 5 M.EV.S
word 6 VALUE
word 7 DUE.DATE
word 8 PROCESS.TIME
word 9 P.ROUTING.SET
word 10 S.ROUTING.SET
word 11 M.ROUTING.SET

The first five attributes of ever" event notice cannot be used


by a programer. He Lannot pack, equivalence, or delete them. He can
do anything he wishes with attributes he defines.
A statement of the form

SCHEDULE AN e-ent GIVEN -rrv•saion AT !;,,


F 4rseso.

(1) Uses the time expression to set TIM[.Ak'v'f%.


(2) Sets EUNIT.A;j;-'e. to zero, 1ndtcrtinX that the event io
being scheduled internally.*

"Set discussion on p. )04.


-300-

(3) Files the event notice in EV.S(I.event) thereby setting the


pointers P.EV.S and S.EV.S and the membership attribute
M.EV.S.
(4) Assigns the values given in the expreoaion list to the suc-
cessive attributes of the event notice, startIng with the
attribute following M.EV.S. If fewer expressions are lieteo
than there are attributes, the remaining attributes are ser
to zero. If no expression list appears and an event notice
has attributes defined, they are all set to zero.

Thus the statement

SCHEDULE A START.JOB GIVEN COST+LABOR, DATE.REQUESTED+1


AND STANDARD.TIME*SAFETY.FACTOR AT time ezrre•8ion

assigns the values of COST+LABOR, DATE.REQUESTED+I, and STANDARD.TIME*


SAFETY.FACTOR to the attributes VALUE, DUE.DATE, and PROCESS.TIME,
respectively, and sets the membership attributes of ROUTING.SET to zero.
In conformance with the conventions followed in CALL statements,
the following input argument forms are equivalent in a SCHEDULE statement:

GIVEN ezpreesion Zi8t


GIVING expreasion list
( expression lis)
So far the discussion has relied on an intuitive understanding
of how time is represented within a simulation program. We now clarify
this issue.
Time is represented in SIMSCRIPT II by a REAL global variable
named TIME.V. At the start of simulation, TIME.V is zero; from then
on, TIME.V is increased to simulate the passage of real time. Each
time an event is selected from the event sets. the value of the time
Pttribute of the selected event, TIME.A, is used to update TIME.V.
Occasionally, the value of TIME.V will be the same before and after
the updating. When this is so. the events that occur during this time
are considered to happen simulta.•eously.
The phrase

at the end of a SCHEDULE statennt states when in the future a specified


event is to rŽcc%,r. Trhe xpreqjsjon is REAL valtwd and car. be thought
of as a .limensionless, •1Alwal-valuol quantity. It is ti is ti". C'at
-301-

is stored in the TIME.A attribute of the event notice, that is compared


against other event times during next event selection, and that becomes
rIME.V when the event occurs. An absolzuta tim is always specified in
an AT phrase. The phrase

AT 0.00

is usually used to initialize events that start off a simulation.

AT TIME.V + 1.5

Illustrates an incremental form of the phrase. It states that the


event being schediled is to occur at the current simulation time plus
1.5 time units. If the basic time unit is interpreted as hours, the
phrase is read, "in one and one-half hours from now"; if the basic
time unit is interpreted as microseconds, the phrase is read as. "in
one and one-half microseconds from now."
In most simulations, simulated time corresv:rds to real time, and
the time units employed are minutes, hours, and days. SIMSCRIPT II
assumes that the units of TIME.V are days (e.g., 1.47 is one and forty-
seven one-hundredths days) and permits events to be scheduled with a
Srel.eZtive time specification. The phrases

IN C'S33 DAYS
IN iri:z,,e:, • e-rta y' MINUTES
IN u-k:,. so': HOURS

schedule the indicated event at TIME.V plus the specified number of


days, hours, or mirtures. The word UNITS can be used instead of DAYS,
and the word AFTER substituted for IN. Conversions are made possible
by assuming th•c the units of TIME.V are days and having two standard
conversion variables. HOURS.V and MINUTES.V are initia:tZed by the
SI.•S'RIPT 1I system to 2.- and 60, respectively, for this Purpose.

They can be changed by a progr.i.er It noed So. Their mode is REAL.


If z.ime is kept it. units ,,f days, hours. and minutes. )ine o'ten

wants to know, not what absolute tiiw it is, i.e.. the vialue of
TIME.V. but what day of the week. hcur of the current aimulated iar.
or minute of the current si1~ilated hour it Is. T1hree svst. fuunct Ionse
described in Tabl-e 5- prov4,! thiq ,apabilitv.
-302-

Table 5-2

TIME CONVERSION FUNCTIONS

Function
Name Argument Mode Function Values Examples

WEEKAY.F REAL time INTEGER 1 - 7 WEEKDAY.F(5.32) - 6


expression day of current
week
HOUR.F REAL time INTEGER 0 - 23 HOUR.F(5.32)- 7
expression hour of current
day
MINUTE.F REAL time INTEGER 0 - 59 MINUTEF(5.32) - 40
expression minute of current
hour

These functions are useful for converting cumulative event times


to calendar-type times during program checkout, and for making decisions
based on day, hour. and minute restrictions vithin a program. Some
examples illustrate these uses:
(1) A check to allow arrival events to occur only on weekdays
or Saturday:

IF WEEKDAY.F(TIME.V)<6, PERFORM START.PROCESS


GO AROUND
OTHERWISE RESCHEDULE THIS ARRIVAL AT TRUNC.F(TIME.V)+I.

(2) An event trace statement put at the head of an event routine:

WRITE WEEKDAY.F(TIME.V), HOUR.F(TIME.V) AND MINUTE.F(TIME.V)


AS "EVENT ARRIVAL OCCURRED DURING DAY%, 1 2, "AT TIME',
1 2, ":", I 2, I.
"nr equivalently:
PRiNT I LINE WITH W(EKDAY.F(TIME.V), HOUR.F(T!M[.V),
HINLfTE.F(TINE.V) AS FOLLOWS
EVENT ARRIVAL OCIJRRED DkkNG DAY *" AT TIME '""

(3) Used vwit a TEIT array of nae as in (2):

In the preamble:

DFINE WEEKDAY AS A 1-DIMMSIONAAL. TEXT AMY


During inttialieat ion•:
-303-

RESERVE WEEKDAY(*) AS 7
READ WEEKDMY
Daca card:
MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
SUNDAY

At the head of an event routine:


WRITE AS "EVENT ARRIVAL OCCURRED ON"
OUTPUT WEEKDAY(WEEKDAY.F(TIME.V))
WAITE HOUR.V(TIME.V), MINUTE.F(TIME.V) AS
"AT TUME", I 2, ":", 1 2, /.
A third kind of event scheduling uses the words

NOW or
NEXT

in statements such as

SCHEDULE AN ARRIVAL NOW


CAUSE A REPLAY(SITUATION, SEGMENT) NEXT and
RESCHEDULE THIS REPAIR NEXT
Events scheduled NOW within an event occur as soon as the event returns
control to the timing routine. They preccde events having the same
event time that may have been scheduled earlier by AT or IN clauses.
If two or more events are scheduled to occur NOW. they are ranked on
their PRIORITY if they are of different classes, on their BREAK TIES
aitributes if these are specified, or on a first-in, first-out basis
if no BREAK TIES attributes have been specified.
It is difficult to describe the operations of these different
SCHEDULE statements by examples that are not imbudded in a simulation

model. The reader should reviev this section to make sure he under-
stands the concepts of:
?rwa!ýn ým event ,t'-

ýy AT, 1N v~k NN)7,hrasors,

snd turn to the example in Sec. - for Instances of hw rh. SCHEDULE


statewent is us*e in simulatlon proarams.
A tvin of the SCHEDULE stateaent is the CANCEL statement, Vhti-h
removes a specified event from Its event set. It ts ý.f the fora:
-304-

CANCEL THIS event and


CANCEL THIS event CALLED vari2ble
As usual, if the first form is used it is interpreted as CANCEL THIS
event CALLED event. The words THE or THE ABOVE can be substituted for
THIS when necessary. The event notice removed is not automatically
destroyed. An attempt to CANCEL an event that has not been scheduled
terminates a program with an error message.

Triggering Events Externall~y

Events are triggered externally by event data cards that are read
in chronological order from external event input devices. An event
card contains the name of an event, the time at which it is to occur,
and optional data, which can be continued on subsequent cards. The
cards are read one at a time, their information recognized and deci-
phered, and event notices created for the events they represent. This
section deals with two issues: the operations performed by SIMSCRIPT II
when external event cards are read, and the format of external event
data cards.
Whean a START SIMULATION statement is recognized, one of the first
tasks performed is reading information about the first event named on
each external event device. The system schedules the first event on
each device and initializes the reading mechanism for subsequent ex-
ternal event triggers. When an external event data card is read, the
event class is recognized and the event time computed from data on
the card. An event notice named event is created, and the event time
and number of the unit from which the event card was read are stored
in the TIME.A and EUNIT.A attributes of the notice.
If the event is of a class that can only be triggered externally,
the event notice contains the five standard event attributes. If it
can also be triggered internally, the notice conforms to the preamble
declaration for the event class, i.e., it might have five words, or
six, or eleven.
After TIME.A and EUNIT.A are specified, the event notice is filed
in the set that corresponds to the event class. Internally and

I.
-305-

externally generated evcnt notices are filed together. They are dis-
tinguished by the coding of EUNIT.A. If EUNIT.A has a special code
value, usually zero, an event notice represents an internally generated
event. Otherwise it represents an externally triggered event and
EUNIT.A is the number of the device from which the external event card
was read.
The format of an external event card is:

1) event name, e.g., ARRIVAL


2) one or more blank columns
3) event time in any of three formats
4) data for the event (optional)
5) MARK.V character (normally *)

The event name and event times are read in free-form by the SIM-
SCRIPT II system. Event data are punched in whatever format a pro-
grammer finds convenient. The MARK.V symbol is used by the system to
advance properly from one set cf external event data to another. As
data for an event can be on many cards, and a program can leave some
data unread, the SIMSCRIPT II system must have a way of advancing to
the start of a new set of event data when it receives a signal to
read in the next external event trigger.
The three formats in which event time can be stated are:

Decimal time units format

In this format, time is specified as a REAL valued decimal number


such as 0.0, 15.56 or 20.0. The number is interpreted as the absolute
time at which the event triggered by the event card is to occur.

Dac-Hour-Minute format

In this format, three INTEGER numbers specify the day, hour of


the day, and minute of the hour at which the event triggered by the
event card is to occur. All three numbers must be present. Typical
event times in this format are: 0 0 0; 0 12 30; 2 15 37; representing
the start of simulaticn, 12:30 in the afternoon of the first day, and
3:37 in the afternoon of the third day, respectively. Hours are num-
bered from 0 to 24 and minutes from 0 to 60.
-306-

Calendar time format

In this format the day in which the event is to occur is expressed


as a calendar day, and the hour and minute of the hour as INTEGER
numbers. For example, the entry 1/15/69 4 30 represents 4:30 in the
morning on 15 January 1969. When using the calendar date format the
year can be expressed as 1969 or as 69; if the form XX is used, 19XX
is assumed. Years after 1999 and before 1.900 must therefore be ex-
pressed completely. Some sample external event data cards are:

ARRIVAL 1/15/69 05 35 *
ARRIVAL 14 05 35 *
ARRIVAL 476.2 *
ARRIVAL 4/17/1960 00 00 *
END.OF.SIMULATION 1000.0 *
SALE 5/10/66 12 00 YOYO 15 2.3 1 1 2 *
SALE 5/11/66 12 30 TOP 22 19.6 2 2 4 *
PURCHASE 500.00 MAGNETIC SOLENOID* 22.50 *
PURCHASE 750.00 RESISTOR* 1.50 *
PURCHASE 750.00 CATHODE RAY TUBE DISPLAY DEVICE* 600.00 *

Before the calendar format can be used, the calendar date of the j
start of simulation must be set to provide an origin against which
calendar time specifications can be compared. This must be done before
the START SIMULATION statement is executed. The origin is set by
executing a statement of the form
CALL ORIGIN.R(INTEGER month expression,INTEGER day expression,
INTEGER year expression)

as in the statements:

CALL ORIGIN.R 4,22,68)


CALL ORIGIN.R(6,2,69) and
CALL ORIGIN.R (FIRST.MONTH,FIRST.DAY,FIRST.YEAR)

Since simulation time is stored in TIME.V and in the TIME attribute


of all event notices as a REAL number, conversions must be made between
calendar specifications and the SIMSCRIPT Il internal representation.
The algorithm that performs this conversion assumes the origin date
is a Monday, and that simulation starts at the beginning of that day
(0000 hours). TIME.V is always set to zero at the start of simulation.
-307-

Four functions are provided to convert year, month, and day ex-
pressions into cumulative simulation times and vice versa. These
functions are described in Table 5-3. As they all depend on a simu-
lation time origin, ORIGIN.R must be called before they can be used.

Table 5-3

TIME CONVERSION FUNCTIONS

Function
Name Arguments Mode Function Values Example

DATE.F 3 INTEGER INTEGER current simula- DATE.F(7,15,58) = 14


expressions tion day
month,day ,year
YEAR.F REAL time INTEGER current year YEAR.F(476.2) = 1969
expression
MONTH.F REAL time INTEGER 1 - 12 MONTH.F(476.2) = 10
expression current month
DAY.F REAL time INTEGER 1 - 31 DAY.F(476.2) = 21
expression day of current
month

NOTE: Time origin set by CALL ORIGIN.R(7.1,68).

DATE.F can be used as a "calendar-type" time format in statements such


as SCHEDULE AM ARRIVAL AT DATE.F(MONTHDAY,YEAR) + SERVICE. YEAR.F,
MONTH.F, and DAY.F are also useful in decision and output statements.
An event notice for the next (first) event on each e^Lernal event
device is always filed in the event set that the data card specifies.
When an externally triggered event becomes the current event, the number
of the unit containing the event data is put in READ.V and control is
passed to the event routine. In this routine, free-form or formatted
READ statements can be used to read the data. The current input pointer,
RCOLUMN.V, is positioned to read the first column after the event time.
A short example illustrates this:
-308-

EVENT ARRIVAL
DEFINE X AND Y AS INTEGER VARIABLES
READ X AND Y AS B 20, 2 I 5

RETURN
END
External event data card

00000000011111111112222222222333333333344444444445
12345678901234567890123456789012345678901234567890
ARRIVAL 525.30 1234512345

2 data fields read by ARRIVAL

position of RCOLUMN.V when timing routine


transfers to event ARRIVAL

A RETURN statement in an event routine means something differert


from a RETURN statement in a routine that is used as a procedure or
function. For one thing, it returns to the timing routine. This
corresponds to the notion that the timing routine is the main or ex-
ecutive program of a simulation and calls on all events. Second, if
an event is called externally, before returning to the event selection
mechanism the next event data card is read from the READ.V unit and
scheduled according to its event time. If the first character en-
countered upon reading the event data is not an asterisk signaling
the end of data for the previous event, data fields are skipped until
an asterisk is found. A programmer is thereby guarded against inad-
vertently reading too little data within an event and throwing all
subsequent event cards out of sequence. Normally, each event reads
all the data provided to it; in no cases should it try to read more,
i.e., pass into Lhe next set of event data. When an event reads less
data than is provided, the programmer can pass over it by moving to
the next asterisk, or leave this task to the SIMSCRIPT II system itself.
The asterisk can also be used to preposition an external event
file before the start of simulation. This is often useful when several
groups of data are contained in one file, or when simulations are con-
tinued from previous runs. The following main program passes over a
section of one of its external event units before starting simulation.
-309-

PREAMBLE
EXTERNAL EVENTS ARE ARRIVAL AND COMPLETION
EXTERNAL EVENT UNITS ARE 5 AND 7
DEFINE X AS AN ALPHA VARIABLE

END

MAIN
READ N '' THE NUMBER OF EXTERNAL EVENTS TO SKIP
FOR 1=1 TO N, DO UNTIL X="*", READ X USING 5 LOOP
START SIMULATION
END

External event data are normally input through cards or through


tapes produced by WRITE stat.,nents. Rarely are external event data
read or written with a BINARY read or write statement. The standard
SIMSCRIPT II external event mechanism reflects this state of affairs
by reading only data in printable form; a progrmmer with a definite
need for binary external event data must find another way of reading
such data into a SIMSCRIPT II simulation program. The following pro-
totype program illustrates one way of doing this. It uses a routine
that reads a binary tape and schedules the events found on it internally.

PREAMBLE
EVENT NOTICES INCLUDE Al, A2,..., AN
END

MAiN
USE UNIT 6 FOR INPUT
CAVL EXTERNAL
START SIMULATION
STOP
END
ROUTINE EXTERNAL
DEFINE V AS AN INTEGER VARIABLE
UNTIL V="*, READ V AS BINARY
READ EVENT.CODE AND TIME AS BINARY
GO TO L(EVENT.CODE)
'L(1)' CAUSE AN Al AT TIME
RETURN
'L(2)' CAUSE AN A2 AT TIME
RETURN

'L(N)' CAUSE AN AN AT TIME


RETURN
END
-310-

EVENT Al
READ event data Ziet AS BINARY

CALL EXTERNAL
RETURN
END

Within an Event Subprogram

When an event occurs, control passes from the SI1SCRIPT II timing


routine to it. Before the transfer, TIME.V is set to the time for
which the event had been scheduled, and a global variable with the
same name as the event is set to the identification number of the event
notice that triggered the event; the notice is removed from the event
set.
If the event is triggered externally, READ.V is set to the number
of the unit from which the triggering event card was read. This
enables the event routine to read data automatically from the same
unit. The following short routine demonstrates a typical externally
triggered event.

EVENT AkRIVAL
CREATE A PERSON
READ NAME(PERSON) AND DESTINATION(PERSON)
LET ARRIVAL.TIME(PERSON) - TIME.V
FILE PERSON IN INTRANSIT(DESTINATION(PERSON))
RETURN
END

The important things to remember about an ex:ernally triggered


event are:

(1) TIME.V is set to the event time.


(2) READ.V is set to the number of the unit on which data for
the event are stored.
(3) RCOLUW4.V is positioned to read the firsL :1lumn after the
time data.
(4) When the RETURN statement is executed, data on the current
external event unit are read until an * ir found, and the
data following the * used to schedule the next cxternal
event for that input unit. Control is then passed to the
timing routine to select the next event.
-311-

If the event has been triggered internally, the event notice


that triggered the event takes on importance, as the additionally
defined attributes of the event notice, if any. are transferred to the
arguments of the event :outine. The event notice is destroyed unless
a contrar) instruction is given. This is done by appending the phrase
SAVING THE EVENT NOTICE to the EVENT statement, as in

EVENT ARRIVAL GIVEN NAME AND DESTINATION SAVING THE EVENT NOTICE

It is common practice to give event notices of internal events


many attributes and save them for use within an tvelt routine and
afterward. Also, event notices can be re" 4. The following short
routines demonstrate these two points:

(a) Event notice used as an entity

EVENT ARRIVAL(NAME,DESTINATION) SAVING THE EVENT NOTICE


LET ARRIVAL.TIME(ARRIVAL)-TIME.V
FILE ARRIVAL IN LIST.OF.ARRIVALS
SCHEDULE AN ARRIVAL("WALDO",CODE3) AT TIME.V + 10.40
RETURN
END
(W' Event notice reused to schedule another event

EVENT ARRIVAL(N,D) SAVI"'G THE EVENT NOTICE


DEFINE N AS AN ALPHA VARIABLE
DEFINE D AS AN INTEGER VARIABLE
CREATE A JOB
LET IDENT(JOB)=N
LET PLACE(JOB)-D
FILE JOB IN LIST.OF.JOBS
CAUSE THIS ARRIVAL("WALDO",LODE3) AT TIME.V + 10.5
RETURN
END

The important things to remember about an internallv triggered


event are:

(1) TIME.V is set to the event time.


(2) A global variable with the name as the event is set to the
identification number of the event notice that triggered
the event. The attributes of the event notice are available
through this variable,
(3) The event notice that triggered the event is destroyed unless
a SAVING phrase is used.
-312-

(4) When the RETURN statement is executed, control passes to


the timing routine to select the next event.

If an event is triggered both internally and externally, and has


arguments, the arguments can only be set if the event is scheduled
internally. The following routine illustrates the basic form of an
event that can occur both ways:

EVENT ARRIVAL(NAME,DESTINATION)
DEFINE NAME AND DESTINATION AS INTEGER VARIABLES
!F EVENT IS INTERNAL, GO AROUND
OTHERWISE READ NAME AND DESTINATION AS B 20, 2 I 10
'AROUND' rest of event program
RETURN
END

5--03 %fODELrIG STArISTICAL PHEIOMEPA

.As simulation is essentially a tool for drawing statistical infer-


ences about the operations of stochastic systems, it is essenLil! •"at
SIYSCRIPT II provide facilities for modeling statistical phenomena.
The heart of the SIMSCRIPT II statistical sampling package is
the function RANCOM.F, which generates a stream of pseudorandom num-
bers between 0 and 1. Starting from an initial value, RANDOM.F gener-
ates successive REAL numbers that can be used in decisionmaking state-
ments or as data in other statistical calculations. The numbers gen-
erated by RANDOM.F are statistically independent of one another.
RANDOM.F haA one argument, an indLA .,tmber that picks one of
several random number streams. RANDOM.F(1) samples from random number
stream 1, RANDOM.F(5) from random number stream 5, etc. All SIMSCRIPT
II programa are initialized with 10 random number streams. The start-
ing numbers for these streams are contained in the INTEGER system ar-
ray SEED.V; traditionally, the first number in a p•eudorandom number
sequence is called the seed of the sequence. As pseudorandom numbers
.re generated new values are ass!gned to SEED.V so that it contains
the current number expressed in INTEGER form.
Should more streaes be needed, a programer can override the de-
fault condition by releasing SEED.V and specifying his vnm array size,
as in:

T'hc algorithm used in this function is implementation dependent.


-313-

MA IN
RELEASE SEED.V(*)
READ N RESLRVE SEED.V(*) AS N
READ SEED.V
START SIMULATION
END
RANDOM.F can be used in IF and WITH statements for decisionmaking,
as in these examples:

(a) IF RANDOM.F(1) < TRANSITION.PROBABILITY, GO BACK


OTHERWISE
(b) FOR EACH CONTESTANT, DO
IF RANDOM.F(CONTESTANT) > FINISH,
FILE CONTESTANT IN POSSIBLE.WINNER
ELSE
ADD 1 TO STEPS(CONTESTANT)
LOOP

RANDOM.F can be viewed in two ways, as generating uniformly dis-


tributed pseudorandom variables between 0 and 1, or as generating
probabilities. The above examples illustrate the use of the function
in the probability sense.
When one considers statistical distributions rather than prob-
abilities, as is typical in simulation models, he I.s interested in
a variety of them. SIMSCRIPT II provides nine functions for generating
independent, pseudorandom samples from commonly encountered statis-
tical distributions. Each of these functions has as its arguments the
parameters that describe the distribution, and a pseudorandom number
stream index. Each time one of the functions is invoked, a pseudo-
random number is generated from the indicated stream and an appropriate
transformation made to convert the number to the correct sampling dis-
tribution. The functions, the argitments, and their properties are
described in Table 5-4.
If the stream number i is negative in any of these functions,
I-RANDOM.F(ABS.F(i)), a quantity called an antithetic variate, is
generated. Antithetic variates are used in simulation experiments
to reduce the variance of estimatea of simulation-generated data.
Discussions of their use can be found in most good simulation texts.
These statistical functions are often used within simulatiun
models to generate activity times. Some examples illustrate their use:
-314-

Table 5-4

STATISTICAL DISTRIBUTION FUNCTIONS

Function
Name Arguments Mode Function Value

UNIFORM.F ep,e 2 , 1 REAL Generates a uniformly


REAL.REAL.INTEGER distributed REAL number
between 0e and e2 using
stream £
NO JAL.F 2.
e1 , e 2 REAL Generates a normally
REAL.REALINTEGER distributed REAL number
with man- 1 and standard
deviation-e 2 using
stream t

EXPONENTIAL.F e, I REAL Generates an exponentially


NiAL, INTEGER distributed REAL number
vi", mean-e using stream i
PJISSON.F e.i INTEGER Generates a Poisson dis-
REAL.!NTEGER tributed INTEGER number
with mean-e using stream i
ERLANG.F e, 11. 12 REAL Generates an Erlang dis-
REAL.INTEGER.INTEGER tributed REAL number with
mean- and k-tI using
stream 12.
LOG.NORMAL.F eI, e2 0 i REAL Generates a lognormally
REAL.REAL,INTEGER distributed REAL number
with mean-e 1 and standard
deviation-e 2 using stream i
BINOMIAL.F iI e, '2 INTEGER cenerates the INTEGER -

INTEGER,REAL.INTEGER ber of successes in i


independent trials, elch
having probability of
success e using stream £2

GAM .F eI, e 2 , I REAL Cenerates a Gana distrib-


REA.'L,REALINTEGER uted REAL number with
mean"e1 and k-e, using
stream

WEIBLL.F el, e2 , i REAL Gengrates a Weibull din-


tributed REAL number vith
shape parister-. 1 and
scale parawrter-e, staing
s_"reami
-315-

(a) An arrival event schedules subsequent arrivals, assuming


that the time between arrivals is an exponertially distributed quantity
with mean of MEAN time units.

EVENT ARRIVAL
statements to process an arrival
SCHEDULE MN ARRIVAL AT TIME.V + EXPONENTIAL.F(MEANp1)
RETURN
END
(b)
Same as (a) but the number of units that arrive is assumed
to have a Foisson distribution with mean 5.

EVENT ARRIVAL SAVING THE EVENT NOTICE


LET NUMBER - POISSON.F(5.O,1)
statements to process the arrivals
SCHEDULE THIS ARRIVAL AT TIME.V + EXPONENTIAL.F(MEAN,1)
RETURN END
(c) Evaluation of n.

r
r

r r

In a rectangular coordinate system the equation of a circle is

i2 + - r ; that is, any point (ij) with i < r and j !.r and

i
2 ++ J < r 2 lies inside a circle of radius r. The area of the circle
2

A square of side 2r has an area w 4r . The ratio of the area of


the circle to the area of the square is ir2 /4r2 a /4.
-316-

If we generate N points (i,j) within the square in a random


fashion, then some of them will fall within the circle, and some will

not. in fact, the proportion of those falling within the circle will
be approximately iT/4 of all the points. If M is the total number of
those that fall within the circle, then M/N is approximately equal to
7r/4. We can estimate the value of w as 4M/N. The accuracy of this
estimate aitproves as N ii.creases, and is proportional to Y9.
This program uses the function UNIFORM.F to generate points (i,j)
that are rarndnmly distributed within a square of side R. It does this
by generging random numbers between 0 and R and assigning them to
i and j. lhc, point (i,j) is somewhere inside the square.

If 2 + j 2 < r 2 then the puint also lies within the circle and 1
is added to M to tabulate this fact. This procedure is repeated N
times. Each time, a different i Pnd j are generated and used to
determine if the point (ij) lies within the circle.
At the end of N point generations, the approximation to w is
printed.

MAIN DEFINE M,K AND N AS INTEGER VARIABLCS


NORMALLY, MODE IS R..L
READ R LET C=R**2
FOR K=, TO N, DO
LET I-UNIFORM. F(OO,R,1)
P J=UNIFOkM.F (C.O,R,1)
IF I - + J**2 < C, AOV 1 TO M REGARD¶.ESS
LOOP
PRINT I LINE WITH t.,(4*M)/N THIIII
THE ESTIMATED VALUE OF PI AFTER *** SAMPLES IS ******
STOP
END

When sampling distributions cannot be characterized by one of the


statistical sampling functions, declarations can be given that define
t,,ble look-up sampling variables. A table look-up sampling vaiiable
haa a list of possible .merical values and their associated prob-
abillties attached to it. It selects a sample valve Ivy generating a
random nuxber and matching it against the possible probatility values.
Taile look-up variables, hereafter called RANDOM variables, are declared
in statements of the form:
-317-

DEFINE nane AS A mode, RANDOM STEP VARIABLE or


DEFINE nmne AS A RANDOM LINEAR VARIABLE

for attributes and global variables.


The first form states that sampling is done from a REAL or INTEGER
valued sampling distribution in a step-like manner; the second states
that sampling is performed with linear interpolation done between REAL
sample values. The following illustrations describe how this ib done:
Assume that a RANDOM variable, or attribute, has the following
sampling aistribution associated with it:

Cumulative Probability Sample Value


0.10 1.0
0.20 2.5
0.25 3.0
0.38 9.0
0.45 11.8
0.60 20.9
0.77 30.0
0.90 33.3
0.99 50.0
1.00 66.7

Note that the cumulative probabilities in the left-har- column


range from 0.0 to 1.0. Sampling is performed by generating a prob-
ability value using RANDOM.F(1), matching it with a value in columr, 1,
and selecting an appropriate value from column 2. Since samples from
KANDOM F are always between 0.0 and 1.0, and are uniformly distributed
between these Pxtremes, the samples drawn from column 2 will be chosen
randomly.
If the sampling variable is defined by the statement

DEFINE SAMPLE AS A REAL, RANDOM STEP VARIABLE

sampling is done as follows in the statement, LET X=SAMPLE:

(1) A random number is drawn from RANDOM.F(1).


-318-

(2) This random number is compared with successive cumulative


probability values until a value is found that equals or
exceeds it.
(3) The column 2 value associated with this cumulative probability
value is returned as the value of the sample.
Examples:
(a) If the random number drawn is 0.20, SAMPLE-2.5
(b) If the random number drawn is 0.45, SAMPLE-li.8
(c) If the random number drawn is 0.65, SAMPLE-30.O
(d) If the random number drawn is 0.95, SAMPLE-50.0

RANDOM variables defined as STEP can be either INTEGER or REAL


valued.
If the sampling variable is defined by the statement:

DEFINE SAMPLE AS A RANDOM LINEAR VARIABLE

sampling is done as follows:

(1) A random number is drawn from RANDOM.F(1).


(2) This random number is compared with successive cumulative
probability values until a value is found that equals or
exceeds it.
(3) Interpolation is done between the column 2 value associated
with the stopping cumulative probability value and the column
2 value preceding it. If i lepresents the index of the stop-
ping probability, C(i) the probability, and V(i) the sample
value, the interpolation formula is

sample - V(i-l) + RANDOM.F - C(i-l) [VMi) - V(i-l)]


c(i) - C i-i)
That is, the percentage by which the random sample exceeds
C(i-1) times the difference between V(i) and V(i-1) is added
to V(i-l).
Examples:
(a) If the random number drawn is 0.20, SAMPLE-2.5
(b) If the random number drawn is 0.45, SAMPLE-11.8
(c) If the random number drawn is 0.65, SAMPLE,23.6
(d) If the random number drawn is 0.95, SAMPLE-42.6

RANDOM values defined as LINEAR can only be REAL valued. Inter-


polations are done in REAL arithmetic and are accurate to as many
as
decimal places dhe computer carries; rounding is done in the above
examples for illustration only.
-319-

Wheneve. a RANDOM variable appears in a "get" sense, i.e., on


the right-hand side of an equals sign, a routine that performs the
above sampling procedure is executed. SIMSCRIPT II generates such
routines using random number stream 1. If the programmer wants to
use some other stream he does the following:
(1) Signals the compiler not to generate a sampling routine by

omitting the wcrds STEP or LINEAR from a DEFINE statement, e.g.,

DEFINE SAMPLE AS A REAL, RANDOM VARIABLE

(2) Writes a routine of the following format:

ROUTINE nmne(index)
RETURN WITH function(F.na'ne(index), stream number)
END

function is one of three systen. sampling routines:

Function Sampling Desired


RSTEP.F REAL, RANDOM STEP
ISTEP.F INTEGER, RANDOM STEP
LIN.F RANDOM LINEAR

F.nwne is the first pointer of the set that contains the


sampling data (see below).
index is an optional subscript or identification number.
Example:
Define SAMPLE as a RANDOM attribute of an entity JOB. The
values of SAMPLE are REAL; sampling is done using LINEAR
interpolation and random number stream 6.

TEMPORARY ENTITIES .....


EVERY JOB HAS A SAMPLE
DEFINE SAMPLE AS A REAL, RANDOM VARIABLE

ROUTINE SAMPLE(JOB)
DEFINE JOB AS AN INTEGER VARIABLE
RETURN WITH LIN.F(F.SAMPLE(JOB),6)
END
RANDOM variables can only be read and sampled; assignments cannot
be made tc them.
Sampling is alwsys done automatically; from a programmer's point
of view a RANDOM variable acts like a right-handed functica.
Because of the special storage assigned to RANDOM variable sample
-320-

values and probabilities, special input treatment is necessary. When


"a variable defined as RANDOM appears in a free-form READ statement,
the following occurs:
(1) Pairs of free-form data values are read until a MARK.V
character appears.
(2) The first of each pair is assumed to be a probability. The
second is assumed to be a sample value.
(3) A system-defined, three-word entity, RANDOM.E, is created
for each pair. The probability value is assigned to its
first attribute, PROB.A; the sample value is assigncd to
its second attribute, IVALUE.A if the variable is INTEGER,
or RVALUE.A if the variable is REAL.
(4) The entities are filed in a set having the same name as the
RANDOM variable. The third attribute in each RANDOM.E
record is a pointer named S.variable.
(5) F.variable occupies the space declared for the RANDOM vari-
able or attribute.
Input probabilities can be cumulative or individual. If cumulative,
the last probability must be 1.0; if individual, they must sum to 1.0.
All RANDOM variables have their probabilities stored cumulatively.
If individual probability values are read, the SIMSCRIPT II system
accumulates them.t
The following examples illustrate how RANDOM variables are defined
and used:

(A) Definition

DEFINE WORDS AS AN INTEGER, RANDOM STEP VARIABLE

Input statement:

READ WORDS

Input data:

0.110 0.2 25 0.35 40 0.55 100 0.8 150 1.0 21u *

tlf any probability is less than 0 or greater than 1, a program


terminates with an error message. If the last probability is 1, the
probabilities are assumed to be cumulative. If the last probability
is not 1, the probabilities are summed so that they are stored cumu-
latively. The last probability ic set to 1.

4____
-321-

Storage of WORDS sample values:

•[ 10 25_40

S0.8 1.0

150 200
0

Use of WORDS:

(a) LET SENTENCE=WORDS


(b) IF WORDS GREATER THAN LIMIT, GO OUT ELSE....

In this example WORDS is a global variable. Sampling probabil-


ities are expressed cumulatively in six pairs of sampling values;
the pairs are stored in six entities in a set named WORDS.

(B) Definition:

DEFINE WORDS AS AN INTEGER, RANDOM STEP VARIABLE


Input statement:

READ WORDS

Input data:

0.1 10 0.1 25 0.15 40 0.2 100 0.25 150 0.2 200 *

Storage of WORDS sample values:


-322-

Same as in (A); individual probability values are accumulated as


the data are read.

RANDOM variables cannot appear in any other form of READ state-


ment, since input of a RANDOM variable "value" obviously means some-
thing special.
If WORDS is an array or an attribute, one can say READ WORDS(I)
but not READ WORDS, if the latter statement is interpreted as a free-
form array read statement. Only a single RANDOM variable data list
can be read at one time. If WORDS is an attribute, READ WORDS is
interpreted as READ WORDS(entity), using Implied subscripting.
It is possible for a program to construct RANDOM variable sampling
sets as well as read them. To construct a set of sampling probabilities
and values for a RANDOM variable called SAMPLE, one writes:

FOR I-1 TO N, or something similar


CREATE A RANDOM.E
LET PROB.Afexpression or perhaps READ PROB.A
LET RVALUE.Afexression or perhaps READ RVALUE.A
FILE RANDOM.E IN SAMPLE
LOOP

5-04 MODEL DEBUGGING AND ANALYSIS

Debugging

The most difficult task in programming, next tu aeciding on the


architecture of a program, is debugging. This can be especially dif-
ficult in a high-level programming language like SIMSCRIPT II, where
many statements are often generated for each one a programmer writes.
Additional debugging difficulties are caused by dynamic storage allo-
cation mechanisms that, by their flexibility, allow a programmer to
work himself into unanticipated situations.
Much of SIMSCRIPT II that has already been described was designed
with debugging in mind. The LIST statement, monitored variables, and
the membership attribute all have this orientation.
Two new definitional rtatements, BEFORE ane AFTER, make it pos-
sible for a programmer to monitor six of the more complex SIMSCRIPT II
statements in an easy way. Table 5-5 names the arguments automatically
-323-

GIVEN to routines called through BEFORE and AFTER declarations.

Table 5-5

BEFORE AND 4FPER ARGUMENTS

BE FORE AFTER

CREATE ----- t Entity identifier

Entity identifier .---- t


DESTROY

CAUSE Entity identifier, time Entity identifier, time

CANCEL Entity identifier Entity identifier

FILEtt Entity identifier, set Entity identifier, set


subscripts subscripts

REMOVE tt Entity identifier, set Entity identifier, set


subscripts subscripts

tNot allowed.
i•In FILE BEFORE and FILE AFTER statements, the second
entity identification nuzbtr is not GIVEN.
itttBy definition, the entity identifica:lon GIVEN for a
REMOVE FIRST or REMOVE LAST is zero.

To use BEFORE or AFTER tracing, a programmer writes a routine


having the same number of input arguments as are transmitted for the
operation being monitored. Suppose it is necessary to check the sub-
scripts for FILE and REMOVE operations in a certain doubly subscripted
set. The statements to this might look like:

Preamble:

BEFORE FILING AND REMOVING FROM QUEUE. CALL CHECK

Routine:
-324-

ROUTINE CHECK GIVEN ENI!TY, SUBI AND SUB2


DEFINE ENTITY, SUBi AND SUB2 AS INTEGER VARIABLES
IF 0 < SUBI < M AND 0 < SUB2 < N, RETURN
OTHERWISE...
PRINT 2 LINES WITH SUBi AND SUB2 THUS
INCORRECT DIMENSIONS IN SET QUEUE
SUB SUB2 =
CALL DUMP
STOP
END
As shown, the routine must be written with the number of sub-
scripts of the set being traced in mind.
The program in Sec. 5-05 illustrates various ways in which BEFORE
and AFTER statements can be used.

Analysis

The principal outputs of simulation experiments are statistical


measurements. Such quantities as the average length of a waiting
line and the percentage 'dle time of a machine are typical. Normally,
statements must be scattered throughout a program to collect this
information, and special summarization statements written to print it
out at the end. Aside from being tedious and time-consuming, writing j
data-c~l'ection and analysis statements is a task to be avoided,
because it clutters up the operating logic of a program with state-
merts whose only function is the collecLion of output inforiation.
Two new statements, ACCUMULATE and TALLY, completely eliminate
this kind of programming. They are preamble statements that instruct
the compiler to generate automatic data collection and analysis state-
ments at appropriate places in a program. All operating programs are
left clear of data collection and data reduction statements.
A statement of the form:

TALLY compu'e 1,'st OF none

performs the same computations as the COMPUTE statement described


in Sec. J-07, but in a global rather than local manner. Each time

tExcept for MAXIMJM(e) and MINIMUM(e).


-325-

none changes value, appropriate accumulations are made to collect the


statistics requested in the compute list. fne is the name of a
global variable or system attribute, subscripted or unsubscripted,
or an attribute of a temporary or permanent entity. If nnv'e is a
global variable, system attribute, or attribute of a permanent entity.
as many variables are reserved to store the statistical counters as
there are elements of name. If n'e is an attribute of a temporary
entity, each entity record is given statistical accumulation attrib-
utes. N(=e cannot be a function attribute, a variable monitored on
the left, or a RANUOM variable.
The preamble generates attributes and routines for each TALLY
statement. A left-hand routine that does data accumulation is always
generated for each tallied variable. The number of generated attrib-
utes and other routines varies with the statistical quantities speci-

fied. Table 5-6 states the cases in which additional routines and
attributes are generated.

Table 5-6

TALLY ACTIONS

Statistical Quantity TALLY Action

NUMBER Attribute generated if MEAN, VARIANCE, STD.DEV,


MEAN.SQUARE, MINIMUM or MAXIMUM requested and
NUMBER not requested

SUM Attribute generated if MEAN, VARIANCE or


STD.DEV requested and SUM not requested
MEAN FUNCTION with name in TALLY list generated

SUM.OF.SQUARES Attribute generated if MEAN.SQUARE, VARIANCE


or STD.DEV requested and SUM.OF.SQUARES not
requested

MEAN.SQUARE Function with name in TALLY list generated

VARIANCE Function with nare in TALLY list generated

STV.IEV Function with name in TALLY list generated

MAX I MUM uses name in TALLY list

MINIMUM Uses name in TALLY list


-326-.

Some examples illustrate the usa of the TALLY statement and the
attributes and functions generated by it:

(a) Use of TALLY with an unsubscripted global variable.

Preamble:

PREAMBLE
DEFINE X AS A REAL VARIABLE
TALLY M AS THE MEAN AND V AS THE VARIANCE OF X
END

Preamble generates:

(1) A left-handed monitoring routine named X, which is called


whenever an assignment is made to X anywhere in the program.
The function counts the number of times X changes value and
accumulates the sun and sum of squares of X.
(2) Global variables A.1, A.2. A - to accumulate the NUMBER,
SUM, and SUM.OF.SQUARES of X for the computations of MEAN
and VARIANCE.
(3) Functions M and V that compute MEAN and VARIANCE from A.1.
A.2, and A.3 whenever they are referenced.

Programmer uses TALLY variables in statements such as:

PRINT I LINE WITH M AND V AS FOLLOWS


MEAN a **.*** VARIANCE - ***.**"
IF V/M > SMALL.ENOUGH, GO AHEAD
OTHERWISE LIST M AND V STOP

(b) Use of TALLY with an attribute of a permanent entity.

Preamble:

PREAMBLE
PERMANENT ENTITIES....
EVERY MAN HAS SOME CASH. IN.POCKET AND OWNS A FAMILY

TALLY AVERAGE.CASH AS THE MEAN AND MAX.CASH AS THE


MAXIMUM OF CASH.IN.POCKET

END
Preamble genermates:
-327-

(1) A left-handed msoititoring routine named CASH.IN.POCKET with


one argument, the index number of the referenced entity.
(2) Attributes A.1 and A.2 to accumulate the SUM and NUMBER for
each entity. A.1 Pnd A.2 are both arravs with N.MAN elements.
(3) A function AVERAGE.CASH to compute MEAN from A.1 and A.2.

Programer uses TALLY variables in statements such as:

FOR EACH MAN. 'IST AVEQAGE.CASH(MAN) AND MAX.CASH(MAN)


FOR EACH MAN, w-OMPUTE M AS ThE MEAN OF AVERAGE.CASH(MAN)

(c) Use of rALLY with an attribute of a temporary entity.


Preamble:

PRFA.BLE
TEMPORARY ENTITIES
EVERY JOB HAS A NUMBER.OF.OPERATIONS

TALLY TOTAL AS THE SUM OF NLhiBER.OF.OPERATIONS

ENC

In progiam:

Preamble genterates:

(1) A left-handed moiitoritig routine named NUMBER.OF.OPEkATIONS


with onc arguwnt, the identification number of the rel'r-
enced entity.
(2) An attribut- namel TOTAL "or the temporarv entity X0,.

Progras=sr u.ses TALLY variables in statements such as:

FUR EACH JOB 1N Q'JEUE(MACHINE), DO


IF TOTAL(JOB) MAX.ALLOWED, GO LOOP
OTHERWISE... REMOVE THE JOB FROM QUEUE(MACHI'E)
PERFORM NEXT.JOO GIVEN JOB
'LOOP'LOOP

from these 4xampies one sees that certain ,-ountvra. ,!e@in*d as


variables or as attributes, ar requIureJ for the stattI - ac& :cvaputa-

tions. These coeunterj are listed in -.


5a-e
-328-

Table 5-7

COUNTERS REQUIRED FOR TALLY STATISTICS

Statistic Counters

NUMBER N, the number of samples

SUM • x,, the sum of the sample values

SUM.OF.SQUARES ~x2, the sum of squares of the sample


i values

MEAN xi, N
2
MEAN.SQUARE x2, N

VARIANCE x, x2 N
2
STD.DEV x x,, N

MAXIMUM M, the value of the largest sample and N

MINIMUM m, the value of the smallest sample


and N

Statistical computations of a different sort are made when the


word ACCUMULATE replaces TALLY. These calculations introduce time
into the average, variance, and standard deviation calculations,
weighting the collected observations by the length of time they have
had their values. Table 5-8 compares the TALLY and ACCUMULATE compu-
tations. To do this concisely, some additional notation must be

defined:

Symbol Meaning
TL The simulated time an ACCUMULATED
variable was set ta its current value
T0 The simulated time at which
ACCUMULATION starts

ACCUMULATE and TALLY statements cannot be declared foi the same


variable. A programmer must decide whether a variable is time-
dependent or not, normally a simple task, and specify one or the
other. An example of the use of the ACCUMULATE statement is given
in the folloving example:
-329-

Table 5-8

TALLY AND ACCUMULATE COMPUTATIONS

TALLY ACCUMULATE

NUMBER N N
SUM [ X [ X*(TIME.V - TL)
SUM.OF.SQUARES [ X X2 *(TIME.V - TL)
MEAN SUM/NUMBER SUM/(TIME.V - T0 )
MEAN.SQUARE SUM.OF.SQUARES/ SUM.OF.SQUARES/(TIME.V - T0 )
NUMBER
VARIANCE MEAN.SQUARE - MEAN.SQUARE - MEAN
MEAN
STD.DEV SQRT.F(VARIANCE) SQRT.F(VARIANCE)
MAXIMUM Largest X Largest X
MINIMUM Smallest X Smallest X

"PREAMBLE
PERMANENT ENTITIES....
EVERY MACHINE HAS A STATUS, A PROCESSING.SPEED
AND OWNS A QUEUE
TEMPORARY ENTITIES....
EVERY JOB HAS A VALUE AND BELONGS TO A QUEUE
ACCUMULATE AVG.QUEUE AS THE MEAN AND MAX.QUEUE AS
THE MAXIMUM OF N.QUEUE
ACCUMULATE MACHINE.STATE AS THE MEAN OF STATUS
END

Let Fig. 5-3 represent the zhanges in value of N.QUEUE(1) over


part of a simulation run. As there are N.MACHINE queues, this is but
one of several similar plots.

L 4 -- 1

3 -
042 - a

0 DD
0 2 4 6 8 10 12 14 16 18
Simulated time in decimal days

Fig. 5-3 -- A sample tinme-series


-330-

The following sums are maintained for the computation of


AVG.QUEUE(1) (see Table 5-9).

Table 5-9

ACCUMULATE COMPUTATIONS

Time value Time value


N.QUEUE(1) began ended Increment Area Sum
(1) (2) (3) (4)-(3)-(2) (5)-(1)*(4) j(5)

0 0 1.2 1.2 0 0
1 1.2 3.0 1.8 1.8 1.8
3 3.0 4.6 1.6 4.8 6.6
2 4.6 6.1 1.5 3.0 9.6
3 6.1 8.0 1.9 5.7 15.3
4 8.0 8.3 0.3 1.2 16.5
5 8.3 11.2 2.9 14.5 31.0
2 11.2 12.4 1.2 2.4 33.4
1 12.4 14.1 1.7 1.7 35.1
0 14.1 17.1 3.0 0 35.1
1 17.1 18.0 0.9 0.9 40.0

If, at simulated time 11.2 (TIME.Vf11.2), AVG.QUEUE(I) appears


in a statement such as LIST AVG.QUEUE(1),, it is computed from Table
5-9 data as 31.0/11.2-2.77. That is, the average number of jobs in
QUEUE(1) from TIME.V=O to TIME.Vf11.2 is 2.98. If at soae time be-
tween changes in N.QUEUE(1), say at TIME.V-10, a value for AVG.QUEUE(1)
is requested, it is computed as [16.5 + 5 (10-8.3)]/10 - 2.5 by the
function AVG.QUEUE.
More complete information on the values attained by til.lied glujal
variables, system attributes, and attr 4 butes of permanent entities
can be obtained by requesting a frequency count of the number of
times a variable takes on specified ranges of valuei. Statement ,of
the form:

TALLY name (r,TO r BY r 3 ) AS THE HISTOGRAM OF nmne,


2 3

define an array name1 with (r 2 - rl)/r 3 + 1 elements, for each element


of nc" 2. The interval between r 2 and rI is divided into classes 13
units wide; if a sample value falls between rI and :1 + r3 a 1 is
added to nwme](l), if it falls between rI + r 3 and r1 + 2r 3 , a 1 is
-331-

added to none 2 (2), etc. To get the average value of a variable over
the life of a program and the distribution of values it has at dif-
ferent times, one writes:

PREAMBLE
DEFINE VAL AS A REAL VARIABLE
TALLY AVERAGE AS THE MEAN AND FREQ(O TO 100 BY 5) AS THE HISTOGRAM OF VAL
END

Whenever VAL changes, observations are summed to provide data for com-
puting AVERAGE, and counts are made in 21 interval counters that indi-
cate the number of times VAL is between 0 and 5-, 5 and 10-, 10 and
15, etc. If a value is less than rI it is counted in the first cell;
if equal to or greater than r 2 it is counted in the last cell.
Compilation of histograms for global variables, system attributes.
and attributes of permanent entities generate histogram arrays of one
more dimension than the variables themselves. This dimension is for
the histogram array, which is reserved by the system automatically
in the following places:

Sampled variable type Place of reservation


Unsubscripted global variable or MAIN routine
system attribute
Subscripted global variable or When it is RESERVED
system attribute
Attribute of permanent entity When it is CREATED

Histograms cannot be compiled for attributes of temporary entities.


Histograms are defined differently for variables that appear itn
ACCUMULATE statements. For them, what is of interest is not how many
times values within a given range appear, but the total time spent in
the different ranges during a simulation run. This allows the calcu-
lation of state probabilities.

Consider the following example:


-332-

PREAMBLE
PERMANENT ENTITIES....
EVERY MACHINE HAS A PROCESSING.SPEED AND A STATUS AND
OWNS A QUEUE
TEMPORARY ENTITIES ....
EVERY JOB HAS A VALUE AND BELONGS TO A QUEUE
ACCUMULATE MEANQ AS THE MEAN OF N.QUEUE
ACCUMULATE STATE.PROBS(O TO 2 BY 1) AS THE HISTOGRAM OF
STATUS
" POSSIBLE VALUES OF STATUS ARE"
"STATUS=O MACHINE IDLE''
"STATUS-I MACHINE DLE BUT COMMITTED"
" STATUS=2 MACHINE ENGAGED''
END

As simulation proceeds, the value of STATUS changes for the dif-


ferent machines. Each time STATUS changes, the length of time the
machine was in that particular state is added to the proper element
of the array STATE.PROBS. Since MACHINE is a permanent entity, and
STATUS therefore a one-dimensional array, STATE.PROBS is a two-dimen-
sional array. The first dimension is N.MACHINE, the second is
3 - ((2-0)/1 + 1).
The percentage time, and therefore the state probabilities, spent
in each state by each machine can be obtained by:

FOR EACH MACHINE,


PPINT I LINE WITH STATE.PROBS(MACHINE, 1)/TIME.V, STATE.PROBS
(MACHINE, 2)/TIME.V, STATE.PROBS(MACHINE, 3)/TIME.V AS FOLLOWS
PROBABILITIES OF BEING IN STATES 0,1 AND 2 ARE *.**, *.**, *.**

And adaptive decisions can be made within a model by statements like:

IF STATE.PROBS(1,1)/TIME.V < STATE.PROBS(2,1)/TIME.V, CALL PERFORM(1)


GO TO L
ELSE CALL PERFORM(2) GO TO L

Each TALLY or ACCUMULATE statement generates a routine for ini-


tializing the counters used in calculating its statistical quantities,
some of which are not initially zero. These routines are named
R.ncvne, where no-me is the variable or attribute being tallied or
accumulated. These routines can be invoked at any time by statements
of the form:

RESET THE TOTALS OF variable Zist


-333-

Thus, the de-'larations of the preamble on p. 332 make the following


statements possible:

RESET TOTALS OF N.QUEUE(MACHINE)


RESET TOTALS OF STATUS(5)
RESET TOTALS OF N.QUEUE(5) AND STATUS(5)
FOR EACH MACHINE, RESET TOTALS OF N.QUEUE

The RESET statement makes possible the preparation of repcts


on a cumulative or periodic basis.
In cases where both periodic and cumulative statistics are required,
the TALLY, ACCUMULATE, and RESET statements can be qualified so that
multiple statistical counters are uped. The statement forms to do
this are:

TALLY variabZe AS THE rneI statistic OF nne2


TALLY variable(n TO n BY n) AS THE nme, HISTOGRAM OF nwne 2
ACCUMULATE variable AS THE name, statistic OF nane 2
ACCUMULATE variab!e(n TO n BY n) AS THE nwneI HISTOGRAM OF nwne2
RESET name, TOTAL OF nc2ne

To generate daily, weekly, and cumulative statistics for N.QUEUE


in the above preamble one would write;

ACCUMULATE DMEANQ AS THE DAILY MEAN, WMEANQ AS THE WEEKLY


MEAN, MEANQ AS THE GRAND MEAN OF N.QUEUE

Periodic events would then print the relevant statistics daily and
weekly, and reset the appropriate counters by the statements:

RESET THE DAILY TOTALS OF N.QUEUE


RESET THE WEEKLY TOTALS OF N.QUEUE or
RESET THE DAILY AND WEEKLY TOTALS OF N.QUEUE

The example of Sec. 6-05 illustrates these statements in the con-


text of a real simulition model.
Since certain ACCUMULATE counters are nonze'ro, RESET must be
called before dynamically allocated variables that are initialized
to zero are used. A recommended procedure is to RESET immediately
after every CREATE or RESERVE for a variable that is accumulated.
Going back to the above preamble, the following pair of statements
should appear in that part of the simulation program that allocates
storage to MACHINE:
-334-

CREATE EACH MACHINE


FOR EACH MACHINE, RESET TOTALS OF N.QUEUE(MACHINE)
If a RESET statement does not use a nawe to qualify TOTALS, alZ
counters associated with the relevant variable are initialized.
Places in a program where variables cannot lie monitored for
TALLY or ACCUMULATE are where array pointers are passed as array
arguments. Consider the following preamble, routine, and calling
statement:

PREAMBLE
DEFINE V'R AS A REAL, 1-DIMENSIONAL ARRAY
rALLY MAS THE MEAN OF VAR
FND

MAIN
READ N RESERVE VAR(*) AS N
FOR 1-1 TO N, RESET TOTALS OF VAR(1)
READ VAR
CALL MANIPULATE GIVING VAR
LIST VAR,M
STOP
END
ROUTINE TO MANIPULATE GIVEN ARRAY
DEFINE ARRAY AS A REAL, 1-DIMENSIONAL ARRAY
DEFINE I AS AN INTEGER VARIABLE
FOR 1-1 TO DIM.F(ARRAY(*)), WITH ARRAY(1)1-O,
LET ARRAY(I) = ARRAY (1)**2
RETURN
END

The values of VAR are changed within MANIPULATE ',jt under the
name ARRAY. Tallying cannot take place.
A final note on analysis has to do with minimizing storage require-
ments for computations of statistica! qu;ntjl.es. The reasons for
wanting to do so are brought out In the following example:

PREAMBLE
PERMANENT ENTITIES.
EVERY MACHINE OWNS A QUEUE
TEMPORARY ENTITIES..
EVERY JOB BELONGS TO SOME QUEUE. AND HAS A VALUE,
A DUE.DATE AND A LATENESS
EVENT NOTICES INCLUDE ARRIVAL AND STOP.SIMULATION
EVERY END.JOB HAS A JOB AND A NEXT.JOB
TALLY AVG.LATE AS THE MEAN OF LATENESS
-3I5-

END

EVENT END.JOBJOB.NEXT.JOB)SAVING THE EVENT NOTICE


DEFINE JOB AND NEXT.JOB AS INTEGER VARIABLES
LET LATENESS-DUE.DATE(JOB)-TIME.V
IF NEXT.JOB EQUALS 0, DESTROY THIS JOB
DESTROY THIS END.JOB
RETURN
ELSE RES,.HEDULE THIS END.JOB(NEXT.JOB,UNIFORM.F(MINMAX,1))
AT TIME.V + EXPONENTIAL.F(REAL.F(NEXT.JOB),I)
RETURN END

In this example, JOB has eight attributes:


each temporary entity
P.QUEUE, S.QUEUE, M.QUEUE, VALUE, DUE.DATE, LATENESS, A.1, and A.2.
The first six names are defined in the preamble. The last two are
generated by the SIMSCRIPT II system as statistical counters for the
attribute LATENESS.
If the logic of the program does not require that the value of
LATENESS be accessible, it is pissible to perform TALLY computations
on it without its being stored. One wishes to do this when he wants
the convenience ) TALLY and ACCUMULATE specifications, but does not
want to waste computer words in storing unnecessary information.
Declaration of a variable as DUMMY allows it to be used in TALLY
or ACCUMULATE statements without having its value stored. Statements
such as

(a) EVERY JOB BELONGS TO SOME QUEUE,AND HAS A VALUE,


A DUE.DATE AND A LATENESS DUMMY
(b) DEFINE GLOBAL AS A REAL, DUMMY VARIABLE
specify that variables (or attributes) are to be treated as REAL or
INTEUER numbers in all copu•tations, but are not to be given storhge
locations. If the statement (a) above were included in the sample
program on the preceding pape. only seven words vould be needed for
each JOB. Savings from DUMMY specifications can be significant in
programs that have large ntabers of statistical variables. These
savings can bo important, e.g., they sight allci 8000 rather than
"300 JOB records to be processed simultaneously.
All preamble-defined variables ond attributes can be declared
-336-

as DUMMY. A DUMMY variable must appear in a TALLY or ACCUMULATE state-


ment. DUMMY attributes are declared in EVERY or THE SYSTEM statements.
DUMMY global variables are declared in DEFINE statements.

5-05 A SIMIULATION EXAMPLE

The example described in this section is deiigned o illustrate


as much of SIMSCRIPT II as is possible in a natural pioblo-m setting.
While it contains most of the language's features, and all of the
ones important to simulation studien, it does not contain them all.
Those features not expressed are described in detail in their respec-
tive sections.
Despite the fact that the features illustrated are not exhaustive,
the example may still seem forced and artificial. This is not sur-
prising, for it is a rare program that requires the full facilities
of a rich and complex programming language. The particular example
"used is an extennion of the job shop model of Chapter 3 of the SIMSCRIPT
t
report.
The plan of this section is as follows: the first subsection
describes the system that is modeled in general terms, presents the
problems the model has been designed to study, and places the rest of
the section in perspective. The next subsection contains a listing
of the complete simulation program follcxed by a set of data cards.
The last subsection works through the program section by section --

end occasionally, where it is warranted, statement by statement --

explaining the syntax and semantics of the statements, permitting


variations where it seems interesting, and backgroun4 mechani•sm
where it seems worthwhile.

The System

The system undet study is shovn abstractly in Fig. 5-4. It is


a shop containing N rroduction centers, each containing Mi identical

H. X. ,iarkowitz, 9. Hausner, and H. W. Kerr, 7:'-.:^'7 A


. 1Prentice-Hall. Inc.. Engleod Cliffs,
-337-

Standard product orders j


Special local orders
Special export ordery

Production
Center,
Production
Center2 Center3
1
Center4 " Lcenter.,
Production Production

Typical product routing Finished goods

Fig. 5-4 -- System under Investigation

machines, and a finished goods inventory storage area. The shop pro-
duces P standard prod&cts for local sale avd distribution, and varia-
tions of t'.te standard products for local and export distributors. Each
product ordered goes through the shop, undergoing processing at produc-
tion centers according to standard routings, production times, and p'-
duct expediting procedures.
Each production center has an in-process inventory area where pro-
ducts in process are stored if they cannot be processed when they arrive
at the center. The production rules of the shop, iai order to minimize
the -value of in-process inventory, always remove partially completed
products from production center queues according to their value.
Table 5-10 shows the entity-attribute-set model of the shop and
its product line.
Aside from the attributes required to accumulate system performance
data, table 5-10 shows the entities, attributes, and sets needed to de-
scribe the static structure of the shop. Permanent e-ntities are used
for production centers and product descriptions, which are fixed in num-
ber. Tcmporary entities are used for jobs and for job processing speci-
fications, which are variable in number. Before going on, the reader
should make sure he understands this characterization of the system.
-338-

Table 5-10

ENTITIES, ATTRIBUTES, AND SETS OF THE SHOP AODEL


Set or
Entity Attribute Coment
PRODUCTION.CENTER NUMBER.IDLE The number of idle machines in a
production center
QUEUE Each production center has a
collection of in-process products,
called jobs
PRODUCT SALES.FREQUENCY Characterizes the frequency with
which orders for standard products
arrive at the shop
NAME Identifies the product
STRUCTURE Each product has a list of standard
operations that have to be per-
formed
JOq Each order ia called a job
VALUE The dollar value of each job
DUE.DATE The time a job is promised to a
customer
ARRIVAL.TIME The time at which a particulaL
job is ordered
EXPEDITE.FACTOR The degree to which a job's pro-
cessing can be speeded up at a
production center
ROUTING A list of production centers
through which a job has to be
processed
FINISHED.GOODS. Jobs can be placed in finished
INVENTORY goods inventory awaiting shipment
THE SYSTEM FINISHED.GOODS. Jobs are placed in finished goods
INVENTORY inventory if finished before their
due date
OPERATION MACHINE.DESTINED The production center at which a
job has to be processed
CODE A number representing a particular
processing operation
PkOCESS.TIME The length of time it takes to
perform a processing task
STRUCTURE The standard production list on
which different production centers
appear
ROUTING The processing operations required
for a particular job
I-339-

The shop operates roughly as follows. When orders for standard


products come into the shop, a standard production sequence is copied
from an order book onto a job's production routing tag. The job is
sent to the first production center, where it is worKed on if a machine
is free. If no machines are available to process the job, it is put
in a work-in-process queue until a machine becomes available. When
a job finishes processing on a machine, its routing tag is examined,
and the job is sent on either to another processing center or to
finished goods inventcry.
The preamble dezlarations for the temporary and permanent enti-
ties specify the items of information that are needed to model the
shop. These are: relev-nt processing center and job characteristics,
and waiting line dis.ipli-.s.
The dynamic structure uf the shop is captured in the two events,
SALE and END.OF.PROCESS. Two other events, WEEKLY.REPORT and
END.OF.SIMULATION, serve only to print system performance data and
stop the simulation. The event SALE is set up to happen both intern-
ally and externally. When triggered internally, SALE represents
either a socal or export sale of a standard product. Two external event
data tapes are provided to supply special order information. In SALE,
jobs are assigned to machines and the system state is changed to
reflect such assignments. Whenever a job is assigned to a machine
an event END.OF.PROCESS is scheduled to terminate the processing,
make the machine available for another job, and pass the job on for
further processing or shipment.
BREAK TIES and PRIORITY statements are used in the preamble to
ensure that system events occur in the correct order when simulation
time ties occur.
At the end of the preamble, BEFORE, TALLY, ACCUMULATE, and
DEFHNE statements finish off the program specification. The BEFORE
statements, and the routines associated with them, are used in one
instance to catch programming errors. The DEFINE statements make
declarations that are necessary, ;ut were not made before. The TALLY
and ACCUMULATE statements collect information on the performance of
the simulated system.
-340-

The simulation is being run to determine how many machines are


needed at each production center to provide "adequata" customer ser-
vice. To study the effects of varying the number of machines in each
center, a TALLY statement looks at the length of time jibs spend in
the shop, and an ACCUMULATE statement looks at the waiting lines that
build up at the various production centers. Some number of machines
will be chosen that balances the cost of degraded customer service
with the costs of additional machines.
The program listing that follows has been written and annotated
to make it au readable as possible. Those statements that are not
clear from the program itself are clarified in the section following
the listing.
-341-

SAMPLE SINSCRIPT 11 SINULATION PROGRAM


A JoB SHOP SIMULATION

PREAMBLE
NORMALLY NOPE 16 INTEGER AND DIMENSION IS 0
PERMANENT ENTITIES..i..
EVERY PRODUCT PAS A SALIES.FREQUIENCY AND A, NANE AND OWNS A STRUCTURE
WRINE SALES.FREGUENCV AS A REAL RANDOM LINEAR VARIABLE
OEFfINE NAMIE AS AN ALPHA VARIABLE
EVERY PRODUICT.PRODUCT HAS A PROOMCT.SALEStSO/Z
EVERY PRODUCT 1ON.CENTER HAS A (MAX* IN.QUEUIE 4 1121AXe QUEUE 121211 IN ARRAY Is
A (IWNUNI41/21, NNU2I2l) IN ARRAY 29 A WhiM. I MS*JMv A NUNBER.IDLE
A0D OWNS A QUEUE
DEFINE NUNBER.IDLE AS A VARIABLE MOMIT'!R&O ON THE LEFT

TEMPORARY ENTITHiS..o...
EVERY JOG HAS A VALUE IN WORD 2, A OUE.DATE. AN AIRIVAL.TINEt
AN EXPEOITE.FACTOR FUNCT:ON@ MAYBELONG TO A C'EUE. OWNS A RO6tING
AND NAY BELONG TO THE WA9TING.SET
DEFINE EXPEDITE.FACTOR AS A REAL FUNCTION
DEFINE VALUE* OUE.DATI AND ARRIVAL.TINEI AS %*AL VARIABLES
DEFINE ROUTING AS A FIFO SET WITHOUT P ANC N ATTRIBUTES
DEFINE QUEUE AS A SET RANKED BY HIGH VALUE
EVERY OPEIIATION HAS A I CODEIL/2) AND NACHINE.OESTINGDI2/2) I INtWORD I
AND A PROCESS#TXNE AND BELONGS TO A STRUCTURE AND A ROUTING
DEFINE STRUCTURE AS A SET RANKED BY LOW COPE WITHOUT N ATTRIBUTE
AND WITHOUT R ROUTINES
DEFINE PROCESS.TINE AS A REAL VARIABLE

EVENT NOTICES INCLUDE WEEKLY.REPORT


EVERY SALE HAS A PROOUCTeTYPE, A PRICE AND A PRIORITY
OE3 IN& PRICE AS A REAL VARIABLE
EVERY ENIt.OF6PROCESS HAS AN ITEM AND A PRODUCER

BREAR SALE TIES BY HIGHE PRICE THMEN BY LOW PRIORITY


ENTERNAL EVENTS ARE N0o.OF.SINULATION1 AND SALE
EXTERNAL EVENT UN4ITS ARE LOCAL.SALES AND tXPORT.SALES
PRIORITY ORDER IS END.OF.PROCESS. SALE, WEEKLY.RE1PORT AND END.OF.SINULATIOW
BEFORE FILING AND REMOVING FROM QUEUE CALL OUEU.CMICK
BEFORE DESTROYING JOB* CALL STAY.TIMIE

DEFINE STAY AS A REAL DUMMY VARIABLE


TALLY AVG.STAY AS THE ifEEELY NEAN* VAR.STAY AS THE WEEKLY VARIANCE, SUN.STAY As
THE NEEKLY SUP. SUP.SGUARES.S:AY AS THE WEEKLY SbN.OF.SOUARtESv AND
NUM.&TAY AS THE WEEKLY NUMSER OF STAY
ACCUMULATE WSUM AS THE WEEKLY SUM. WMNU AS THE WEEKLY MM*ROER AVG.WJUEU AS THE
WEEKLY IWAft NAK.GUSUE AS THE6WEEKLY MAXINUM AND FRIGID TO Z9 BY 11
AS THI WEEKLY HIS1 TOGRAM OF N.Oueut
ACCUMULATIE MSUN AS Tht MONTHLY SUP, NPIUM AS THE MONTHLY NUNBER, AVG.IN.QUEUE AS
THE MONTHLY MIEAN. NAR*IN.QUfUE AS THE MONTHLY MAXIMIUM OF N.QUfUE
THE SYSTjM OWNS A FINISHED.60005.INVENTORY
DIEFINE FIMISNED.GOOOS.INV*MTDRYV AS A SET RANKED BYIUE
DEFINE LOCAL TO NEAN DEFINE IvJRL.N AND N AS SAVED INTEGER VARIABLES
DEFINE WOEES TO MEAN *MOURS.V0T HOURS
DEFINE PRIORI TY.FUEQIONCY AS A -i-DIMENSIONAL ARRAY
DEFINE: TITLE AS A TIET VAIRIABLE
DEFINE WEEKsCOUNTER AND WAVE.'FLAG AS 1INTEGER VARIABLES
DEFINE AVERAGE AS A REAL FUNCTION WITH I ARGUMANT
END
-342-

MAIN
OINIT1ALIZIo PERFORM INITIALIZATION
LIET OrElTUEEN..VoTRAC1o START SIMULATION

PERFORM NeXT EXPERIMENT of


Pon EACH Joe IN PINISEOe.6001SeINVMINTORYo 00
REMOVE THE JOS FROM PINISHIO.GOOOS.INVENTORY
DESTROY THE JOI
LOOP
FOR EACH PRIOOUCTION.CENWWIR,
FOR EACH JOB IN aiEVE. 00
PON fACIM OPERATION IN ROUTING, DO
IRemove THE~ OPERATIrON PRtOMl ROUTIlNG
DESTROY THE OPERATION
LOOP
RIMOVIETE iO PROM4 QUEUE
DESTROY THE JO4
LOCO
PUO EACH PRoOUCro DO
FOR EACH OPERATION IN STRLCTURIe 00
REMOVI THE OPERATION FROM THE STRUCTURE
ESTROlV THE OPERATION
LOOP
ALSO FOR EACH RAN10O0.E INs SALIS.FREOUIENCV, O0
REMOVE THE RAWAON.E FROM SALES.PREOVUENCY
D1SlROy THE RANOOM.E
LOOP

RELEASE NAME. FPSTRUCTURlEL.STRUCTURE, N.eSTRUCTURU. FP.SALE S.PREOUIENCY


PROOPJCT.SALES NUMSiU foeUEUE, L.EUtE. *.QOUEUE@ MAXo.I.QUEUE.
R.I01oOLE,
MAIEI.0sw USUM. "SUMS NMJM, MqNUM
RELEASE PPIORITV.PREOUENCY
ERASE TITLE
ROSET TOTALS Of STAY
FPU EACN PROMCIION.CINTERo RESET TOTALS OF N.OUGUE
LET WEES.COUNWTERO
WRITE AS 00066,/
LET IAI.PFLAG-0

O RIUSI EXTERNAL EVENTS IN NEXT EXPERIMENT


REW6INO LOCALoSALES AND IEPORI.SALIS

60 IN1IIALIlE
STOP IWO0

OVTSN4d PUS IMMEALIRATION


LOCAL
0010I1 Po t0 MlAN PRIORI0y.PalEowuCy
"0PlNt SP to mEA SA&ES.PFIEANNCV
Defles C"IIc AS AM ALP"& VMIAisOI
tIv IWf.W/ I
INPUT TITLE
If 1OPF.V.U. PIRI I LINE AS FOLLOS
1110 of DATA ol
STOP
EL Ie
-343-

RADi N.PROSUCTION.CENTER
CREATE EVERY PRDOuCTIONACINTIR
FOR EACH PROOUCTIO11.CENTER.t READ NUNSELIOLE01.1
READ N.PROOUCT
CRERvu EVERY PRODUCT
RESERVE PRIMRITY.PREOUENCYloo*l AS NI.PROh)UCT IITS
FOR GACO PRODUCT. DO
READ NAPE
READ SALES.FRIOUEUCY
RESERVE FR EON ITY.FREUOENCVIPROIIUCT94I AS PRODUCT
FOR li' TO PRODUCT. READ PRIlORITYbFPPfU2UNCYIPftDUCTvII
UNTIL 140SE IS ALPHA. 00OTHIS.....
CREATE All OPERATION
FILE THE OPERATION IN STRUCTURE
READ COOlo XACHINE.OCSTINED AND FIOCESS.TIME
LOIP
SKIP & FIELD
CAUSE A SALE IN SF "OURS
LET PFOOUCT.TVPlsPROOUCT
LET PRICEsPROOUCTORAINWO.FiII
LET PNIORIT~sPFUPARDUUCT. TRUNC.PFIPI""Ill
LOOP

READ LOCAL.SALES9 EXPORT.SALES AND SAVE.TAFE

REA" ""TON. DAY AND YEAR CALL ORIGIO.R4NONTH.DAY AND YEARI


READ CHECK1 IF CHECK EWUALS 0=0. CALL REPORT RETURN
OTHERWISE MIN1T I LINE AS FOLLOWS
EITHER TOO M4UCHDATA OR DATA HAS SEEN READ INCORRECTLY
STOP ENO

EVENT SALE IPROOUlCTs PRitCE.PRIORI TVI SAVING THE EVENT NOTICE


DEFINE SP( fOEMEA SALES.FRkEUENCV
LOCAL
IF SALE IS ERTERNAL. READ PRODUCT. PRICE AND PRIORITY AS 0 3091 So 0410*31. 1 S
REGARDLESS ADO I TC PROPJICT. SALESSIPROOUCT9 TRUNK.FIPltIClIoI)I
CREATE A JOII
LET VALU~wPRkICEl
LET DUE.SATEsTIMI.V * PRICE * PRIORITY
LET ARRIVAL.TIMlE.TIME.V
IF SALE IS INTERNAL.4t
FOR EACH PIECE OP STRUCTURE. FILE PIECE IN ROUTING GO TO JOB
to PROCESS SPECIAL ORDERS
OTHERWISE UNTIL NODE1 IS ALPHA. OSl THE FOLLOWING*..
FOR EACH PiEsE IN STRUCTWIE WITH COOEIPIE11Cls 0 N.
FIND THEl FIRST CASE# IF NONE 60 1D LOOP
FILE PIECE IN ROUTING
OLGOOP LOOP
JOjll noW ATTENU.TO.JOSl
IF SALE IS ENTERMAL.o DELROYTH fe

II
ALE RETURN
OTHERWISE.....
SCHEEWLE THE M#LIFsODUCT. PpIRADMFI.PAIDWIIY.FREooENCYIPROCIUCT.

REUR 0"C
ROUTINEl To [email protected]

S4JSTIaCT I PROM ISLE


ERo. P19POW ALLOCATION

MAINE FoR ALLOCATI&O


R#ownI" Fpst OPERATION PROM 1HIs Rout ing
po
SCEWEAN ENSeW.PRoCs$ GOVPEW AN POMm~TKO.CEf"to
I
RETURHOERS
-344-

ROUTINE EEPED1IT.PACIom
IP TINA.V IS GRIAVE! IthAN DUE.OATE RETURN WITH 0.5 ELME
RETURN WITH NINJPIF.,-i:,)POCSSTNE1

UP" NEMOOPeP0OCISS SIVEN JEAND PRODUCTIONoCaNTER


IF ROUTING is lEFTY, IP 0UE4SATE 0' VIN.V#
PESTROV THIS Joe 00 TO PC
ELSE PILE THIS JOG IN PINISNEO*GOODSoIMV9NTORT G0 TO PC
OTHIRWISE CALL ATTENO.TO.JO0,

IF NVew IS EMPTY,
ADD I TO NUINSER10.IO RVTURN
LSE REMOVE THE PIRST JEPOOP SUIEUE
PERPORM ALLOCATION RETURN
INC

EVENT PUB WEERLI.oREPORT SAVING THE1 *VENT NOTICE


RESCMEO10.E THIS WEEKLY.REPORf IN I V1F4
ASS I To MWENO.CUUNTER
NOWREPORT
RESET WEEKLY TOALS OF STAY
NOI 1ACM PROSUCtION.CENTERe REU41 WEEKLY TOTALS OP N.OUEU1
IP 0OO.PIWEEI.CUIN1TERs4ImO9 FOR EACH4 PROSUCTION.CENTER. RESET MONTHLY TOTALS
OF N.OmuE ELSE
RETURN END

EVEINT FUR ENO0.OE.SINMUATIOV


FORlo 10TO VNTS.Vo FOR EACH NOTICE IN EV.SiII,. 00
REMOVE THE NOTICE FROM EVeS411
SESTROT THE notice
LOW
LIST PRMIUC.SaLES
RETURN *No

ROUTINE foot waES-CHECK GIVEN ENTITY ANS a


LOCAL
if I LE I LE NP*MOOUCTION.CGNTER* RETURN
OTHERVIS..* PRINT I LIOE WITH I AS FOLLOWS
STOPPIO IRVING TO REFERENCE QUEUE1 too
TRACE STOP END

ROUTINE Foot SIA19710E GIVEN JOG


LET STAVuTIME.V - 4, *IVAL.IINEIJOSI
RETURN END

ROUTINE TO TRACE
LOCAL
It PINIS4119*001S.INVENTORV IS EMPTYp. SO AROUIND
ELSE FOR EACH dOE MNPNSE.OO.NET UNTIL DUE.OATE 31 TINE.Vo 00
me"OVE To Joe PROM FlatsMES.GO0oSIN"""TORY SESTROY THE JOG
LOOP
SO VS E01.0.PSKIESS9 SAL@* UEINGY.REFPORV AND 101NS.5P.ILATION PER 1V1NV.V
I,*ENOFW.PRocisso WRITP ITEM PRODUCER* TINE.V AS 61IP~oo I So 'STOPPEO.
'PROCESSING, ONMNACHINE*# I S. 0 AT TINE".OIIO.31s I
RETURN
'SALE0 UNITI TSNE.Ve PWOOC.TVPE. PRICE AMWPRIO&ITY AS OSALE OF TYPE', I So a
0 MROOUT AT VINE.'. 0490.3). a FOR lot DIG 1),* aPRIORITYO"s I so
I RETURN
'WEERLYdREFUTO
&I TV" .3~ VNN
-345-

LEFT ROUTINE NUNURICLEINI


DEFINE J AS A SAVED, 2-01PENS tONAL ARRAY
DEFINE 9 AS A SAVID, 1-01NENSIONIAL ARRAY
ENTER WIT" N
IF TAPE.FLAGoOt LIT TAPE.FLAGol
RELEASE J AND K
RESERVE R401 AS N.PRODDITIUN.CENTIR
RESERVE J480*1 AS 100 IV N.PROOUCTION.C11NTER0
REGARDL.ESS ADD I TO AMN
LIT JIKIN),I.Nlo
IF KIN1sIOO. WAITE N AS I 3 USING SAVI.TAPE
FOR lot TO 100, WRITE J11901 AS 1 3 UStG, SAVE.TAPE
WAITE AS I USING SAVE.TAPE
REGARDLESS POVE FRON W
ROTAN END

ROUTINE To REPORT
LOCAL
IF TIXEoVmOv
START NE0 PAGE 90AND0 OUTPUT TITLE
SKIP 2 OUTPUT LINES
PRINT 3 LINES AS FOLLOWS
FPA 0D '1C 1 D AT A
"HAME SALES FREQUENCY PRODUCTION SEQUENCE
PORS. VALUE CODE CTRm TINE
FOR EACM PRODUCT. Do
LET I.F.SALEIVFREQUENCY
LET J.F.SWRIJCTURE
PRINT I LINE WITN NANE. PROS.AIII, RVALUIa.AIII, CODEIJI.
NACHINEODESTINED(JI AND PROCESSOTINIIJ3 THUS
5,05 0.00 0 *04 **
IF 1-00t LET IoS.SALF~afR6GENCV4I1 ELSE
IF J-%449 LET JOS.STRUCTUR4IJ MELS
If Ioll AND JwO. GO TO OLOOPQ ELSE
If Ift.O AND JwOp PRINT I LINE WITH PROS.AgII AND RVALUE.AiII THUS
ELSE IF IoG ANM J..D. PRINT t LIONE WITH CIDEIJI. PACNINE.DEDSTINEDIJit
AND MMICSSTNel'IJI,1 THUS
"0 0.00
00
ELSE If [email protected] PRINT I LINE WITH PROS.AIII. RVALUI.AIII. CODEIJ1,
NACNINEMOSTINEDIJI AND PROCISS.TINEIJI THUS
06*0 0.00 00 00 0.00
OLOSP LOOP
SKIP 2 OUIPUT LINES
PRINT 2 LINEIS AS FOLLOWS
PROD 0U CTIO0N CEIN TER D AT A
CENTER 0110ER OF NAHINES
FOR EACH PROOUCTION.CENTIR9 PRINT I LINE WITH PROCUCTIMNCERTER Am)
NUNSER1. IDLE1 THUS
00 00
SKIP 2 OUT`PUT LINES
PRINT I LINES AS FOLLOWS
1 06 T I A L E VEINT S
EVENT TYPE TINE
FOR 1.1 To EVENTS.V. Foot EACM J IN #V.sM@t
PRINT I LINE WITH I AND TINI.AIIS THUS
REGRDLSS....0 00,00
START NEw PAGU
PRINT I LINE AS FOLLOWS
PRINT 3 LINES LIKE THIS*....
W IEEKL Y REIPORaT

PRINT 2 LINES WITH AVG-STAY AND VAReSTAY AS FOLLOWS


JOG STAY STATISTICS &ARll AVERAGE STAY. 0.00
VARIANCE 0.06
SKIP 3 INITPIT clINEs

I
116GIN REPORT
SKHIN HEADING
PRINT I LINES AS FOLLOWS
PRISUCION CENTER VJEUEING REPOT
CNTS Avg. stEoE MAX. OUEUE
ENo *'HEAOING
PONREACH PAGOUCTION.CENTER,9 PRINT I LINE WITH$ PROOKTION.CENTIA,
AVI.UEUEl AND FAK.&UIW Tus
000.00 0

ENG 4:001RT

'o
-346-

PRINT I LINE WITH AVERAGIIAVEoQUfU|osIt LIRE THIS


OVERALL AVERAGE1tUIE LENGTH Of ALL GUSUIS IS eeoc
SlIP I OUTPUT LINS
PFO 1AGm PRODUCTIONOCENTE~m Do
OI610 REPORT PAINTING FOR le TO 29 IN GLOUPS OP 9
111161"GAD106
PRINT I LINE
"HISTNM•N WITH LINOTM
0 QUEUE PROUSCTION.CENTIR LINECENTER
THIS *0
FOR PRODUCTION
too 00 "IAOINO
PRINT I LINE WITH A GAOUP OF FRIEOIPRODOUCTIOSoCENT Mto2I FIELOS THUS

LOOP
IP @OO.PIWNHIOCOVUNTERto$-%Oa RETURN
OTHERWItMeoo STOAT NOWPAME
PRINT I LINt AS FOLLOWS

SUIP 3 VONPUT LIMRS


o REPORT
Si4n
ontoe HIAO UGA
POINT 2 LINES ASAFOLLOWS
PRODUCTION CEloAS
cilia V-IRIUMAL RX.
A QUOU11
Avg. ARtPRAQUfE
ENO "HEADiINGL
P SdiGN TROBICTIONwCENTI, PRINT IELINE ISTHPROEA CTION
A INTA
SETU1l.0ulluR Am RS1oI0oUMA THUS
IN0 to RElPORT
PRINT I LION WITH AVdIGAGIIAVoI.•M[UEU1411IK tTHI•uS
OERALLt &OAvt 11 VA LENGTH OF ALL QuUEUS IS o*00
UTURN
Mao

sOUTINE FOR AVERAGE GIVIN AMAV


LOCALb
DEFINE ARRAYr AS A 1--lntNSlOMIAL AMAtA
00t JuilrTOJ91o14AMtdY14119 COMPUTE| x AiS VTo MAN OF dlMllYMJ
RTlJURN WfYm R
-347-

SAPli 0D1ATP0* SEVERAL JO. SOW 101tI1tUVS DUSIUP 1wC LEVEL So SECTION S.09
.0V11666W SIULI,01 CAN 1|1060 OVER SEVERAL CMOS
PROG1lso.....lITLIS. AS SIN1151H
W AME INOGO III A NA OeVCHMAACTEI

t0o 0coa 10.0 0o.0 1.0 0.ays 20.0 1.000 25.


I 1 OvP a G0.sp 1 0*0
V0TO 0.10 so. 0.11 9.6 0439 7.2 0.40 9.0 0.61 0.4 0.95" £9.2
1.40 6.000
aa Is 1 I.2 I6 10.6 If 9 0*2 Is 2 lose
,ALL 0.1 1o. 0.1 1.0 0.0 3.6 0.4 4.0 0.1 9.6
12 14.2
9 .It 49* a 1a 3.2 is S 2.0040

THIS 'i A VEILS CARD POR THE SICOWt SIONA4110 llPIlANINT OF TOO SERIaS
(+8T6 CMIs FOD THIS IIPIEIN11T VILL HAVE 9OU SAN POSIkm AS THOSE OF THE
PARVIOUS lXPEllNINW am0 WILL viv o1WI all w*me CARDO

lTt POI•IOWIW CMOS mi SamiPS OF TOU DATA ,lMOS PUOC..w FOR ON OF ITo TWO
IXTl41mL v*
yIgiS TAPES .. ..... +... THIS s
Ji A Salome rum 1,14 rot6

SAL 711161 11 00 2 l.go a Is I? to 0


SALE 1/2140, i 3 5 1 0.91 1 1 a 3
SALE 119/64 ol so a 5.50 a 16 I7 Is *
SALE 113144 07 00 1 .01 1 *
It0o 3*0
IM00.OP.SNULAIIION 911/49 12 00 0

I
-348-

Comments on the Simulation Proaram

The program is arranged functionally and is discussed as it


appears. The order of the program is: preamble, main rouivne, ini-
tialisation, events and routines of the simulation model, routines
for monitoring, debugging, and analysis.

PEAMBLE

The preaste is divided into seven sections: permanent entities,


temporary entities, event notices, event control, debugging, analysis,
and miscellaneous declarations. Most simulation programs are organized
this way.
One compound and two sialts permanent entities &re declared. The
special features of each are:

PRODUC1 his a RANDOM attribute and an ALP.'A attri!bute, each of


which requires definition in a DEFINE statement.
PRODUCT.SALES, the single attribute of the compound entity
PRODUCT,PI)DUCT is intrapccked to cousarve ttorage space.
PP IDUCTI(M.CENTER has tvo pairs of attributes that are packed in
the same array, and one attribute that Is monitored. The packed
attributes use field-packing, equivalence, and drray sp,;cifica-
tion. The monitored attribute requires an additional DEFINE
statement.

PRODXJCT.SALES could just as easily have been defined as a global


array or as a tvo-dimensional system attribute. An a global array',
however, it could not have been packed. As a system attribute, it
youAd not be eligible for implied subocripting.
"Vo te*orary entities are declared. Thn special features of
each ý%re:

JOB has one attribute placed in a specift.- wnrd in its entity


record, and has a finction attribute. The N,:nctton attribute
requi'res a DEFINE stattment to Ieclare its mode.
Tuo sets in vhich a J0N participatc. have their implied properties
mnodified by DEFINE statements.
ivo attributes of OPERATION are pachod in the first word of tthe
entity record.
A set to which an OPRAT',ON belcnlts has its removal routines
;#leted bv a DEF'NE statement.

I,
-349-

Three event notices are declared. The special features of each


are:

WEEKLY.REPORT has no attributes and neither owns nor belongs to


sets other than the standard one defined fo all event notices.
Ore event, SALE, treaks ties among competing event notices through
a BREAK TIES declaration. The other internal events break ties,
if they occur, on a first-come, first-served basis.

Tuo external event types, END.OF.SIMULATION and SALE, are declared.


Two input devices are dezlared as suppliers of external event triggers.
The priority order of the four event types is declared in a PRIORITY
statement.
Lwo BEFORE statements are used, Each states that a certain rou-
tine is to be called before a specified action takes place. The argu-
ments to these routines are not stated, but implied. (See Table 5-5.'
One TALLY and two ACCUMULATE statements are used. The special
features of each are!

The TALLY statement compiles statistics for a DUMMY variable.


This variable is declared in a separate DEFINE statement.
All of the s.atistical counters used in the TALLY and ACCUMIJLATE
statements arr defined so they can be released. If they were
not named, they would be given local names such as AM and A.2.
FREQ is a two-dimans!.onal array. The first dimensiun is an en-
tity index. The variable for which it accumulates a histogram
it an attribuite of PRODUCrION.CENTER. The second dtmension is
the histogram index and is an integer between 1 and 26.

The remaining statements are self-explanatory. They

Zeclare a syter-owned sat.


Use DEFINE TO IEAN statements to create shorthand notation.
Declare four global variables: a tvu-dimensional array, two
INTEC{IR variables and # TEXT variable.
Declare a functUoi and specify the number of arsumonts it t•ust
always have.

MAIN FIOC1AI(

The "ein routin, has three functions: it Initiallzeu the model


so sim.ala, ion can start, it transfers contrnl to the timing routine
when initlalization is complete, and it resets the entire system ýo
-350-

an "empty" condition at the end of a simulation run so another experi-


ment can begin,

I Initialization takes place in the routine INITIALIZATION, which


called by MAIN.
is After initialization, the SUBPROGRAM system vari-
able BETWEEN.V is set to the routine name 'TRACE', indicating that
this routine is to be called before each event of the simulation.t
Simuiation is then begun by the START SIMULATION statement that re-
moves the first event from the sets EV.S ( ) and transfers to it.
Simulation proceeds until an END.OF.SIMULATION event occur-.. This
event, aside from its obvious task of reporting the results of the
simulation experiment, empties the events sets, EVZS ( ). When
END.OF.SIMULATION returns control to the timing routine, the lack of
scheduled events causes control to pass to the statement after START
SIMULATION. In many simulations this will be STOP. In this example,
it is the first of many statements that release and destroy all per-
manent and temporary entities for the reinitialization of a new
experiment. After these statements have been executed, all the
memory structures set up by the previous experiment Vave been erased.
In performing this erasure, the system set FINISHED.GOODS.INVENTORY,
and the sets owned by all the permanent and temporary entities, are
emptied and their members destroyed. Finally, all attributes of
permanent entities are released. Special features to notice are:
The PRODUCTION.CENTER loop, in which operations owned by jobs
that are owned by production centers are successively removed
tnad destroyed.

The RANDOM variable SALES.FREQUENCY is treated as a set when it


is emptied.
All permanent entity attributes, including set pointers and
statistical accumulators, are released.

In many programs, so extensive a reinitialization process will


not be necessary. For example, it is usually sufficient to zero out
all attribute values and empty all sets. This example has been
written to ill jtrate what seems to be the worst case.

TSee Sec. 5-06.

m
-351-

In situations where single simulation tuns arc made and no re-


initialization is necessary, the initialization routine can be released
and its space regained for array and entity storage. The following
routine shows how this is done.

Add to preamble:

DEFINE INITIALIZATION AS A RELEASABLE ROUTINE

Use this routine:

MAIN
PERFORM INITIALIZATION
RELEASE INITIALIZATION
START SIMULATION
STOP END

PROGRAM INITIALIZATION

INITIALIZATION starts with some &eciarations. The first takes


advantage of the DEFINE TO MEAN statement of the preamble to define
some local INTEGER variableo I, J, K, L, M, and N. The next two
statements are local DEFINE TO MEAN declarations that create a short-
hand notation for two lengthy variable names. The last declaration
declares a local ALPHA variable that is used to verify that all in-
put data have been re&d,
Since a mistake may have been made in setting up a simulation
run, EOF.V is set to 1 to give the program control over the actions
taken when the end of the input data file is reached. If, when read-
ing TITLE, an end-of-file is encountered, EOF.V is set to 2 and this
fact is picked up in the followiag IF statement.
A sequence of simulation experiments can also be stopped this
way. When all the data for a sequence of runs are exhausted, these
statements will stop the program.
The INPUT statement zeads characters from the current input unit
READ.V until an &aterisk,the MARK.V default symbol, is reached. A
typical simulation TITLE card might be:

SIMILATION RUN NO. I JOB SHOP WITH 10 CEN(ERS *

If some symbol other than * is to be used as a TFXT terminator, a


-352-

statement such as LET MARK.V-"?" is put at the head of INITIALIZATION.


A value that is the number of production centers is then read,
and used to reserve the arrays that hold the attributes of PRODUCTION.
CENTER. This value is also used to read in the number of machines in
each production center, which are all idle at the start of simulation.
A similar process then takes place for PRODUCT. It is more com-
plex in that a richer variety of data structures is associated with
PRODUCT than with PRODUCTION.CENTER. The data structures are:

PRIORITY.FREQUENCY, which is a "ragged table" as described in


Sec. 2-08
SALES.FREQUENCY, which is RANDOM variable
STRUCTURE, which is a set with OPERATIONS as members

Also, an initial local SALE for a standard product is scheduled


for each product type. In scheduling these sales, the PRICE of eac'I
SALE is a random variable between 0 and the product type, e.g., a
type 3 product can be sold for between $0 and $3, and the PRIORITY
"assigned to a sale is determined by a random draw from the PRIORITY.
FREQUENCY table.
At the end of initialization, the numbers of the input devices
for the LOCAL.SALES and EXPORT.SALES external event units are read.
This al~own devices tj be changed beLween simulation runs. Finally,
the ORIGIN.R routine is invoked to set the simulation calendar so
that calendar dates can be used on the external event tape@.
If the lasL data field read Is not the character string OK, the
run teruinates with an error message.

EVENTS AND ROUTIN'ES OF THE SIMULATION ?WDEL

The event SALE is vritten to react properly to both internal and


external event triggers. The event creates a job, determines its
routing through the shop, end starts it in its processing sequence.
If the sale Le internal, i new order is scheduled for the sae product
some time in the future.
The EVENT statement defines SALE as an event routine vwih three
input arguments. It also declares that vhen a SALE event notice is
-353-

selected as the next event, the first thrae programmer-defined attri-


butes of SALE are to be assigned to the local variables PRODUCT,
PRICE, and PRIORITY, and that the event notice is not to be destroyed.
An important point to note here is that PRODUCT, PRICE, and PRIORITY
are local variables; they are not the same variables as wnre defined
as attributes of the event notice in the preamble.
The first two statements are local declarations we have seen
before. The third statement is the one that allows SALE to be used
with both internal and external event triggers. It says: if SALE
has occurred externally, read three data items, otherwise do not read
any data. Regardless of how the event was triggered, values get
assigned to PRODUCT, PRICE, and PRIORITY.
The next statement adds 1 to an element of PRODUCT.SALES, counting
the number of times particular products are sold at different prices.
The next section of code creates a JOB entity and assigns values
to its attributes. The JOB is the entity that will flow through the
shop, and will represent the sale from now on. If SALE is triggered
internally, it is a sale for a standard product, and the standard
sequence of operations for producing that product is transferred from
STRUCTURE(PRODUCT) to ROUTING(JOB). Notice that implied subscripts
are used in the program for both STRUCTURE and ROUTING. If the SALE
is triggered externally, it represents a possible special order. As
special order operations are subsets of operations that produce
standard products, data are read that select a subset of operations
for producing the order and sture it in the JOB routing set.
With this, the task of SALE is almost completed. Processing of
the now completely specified JOB is started by the routine ATTEND.TO.JOB.
After this routine deals with the Job. it returns to SALE, where
arrangements are made for the next SALE. If the SALE just processed
was triggered externally, the event notice is destroyed and control
returned to the timing ma;hanism. The neyt exrerna1 event will be
selected automaticaily by the timing mechanism from '-he external
events units. If the SALE was triggered internally, the 2vent notice
is reused to achedult another "sle for taiis sa.e product. with a
different price and priority. The time at which this sale is to
-354-

occur is determined by a random sample from the RANDOM variable


SALES.FREQUENCY(PRODUCT); again, implied subscripting is used.
ATTEND.TO.JOB uses the routing of the current JOB to select the
production center in which the first operation is to be performed.

The first statement in ATTEND.TO.JOB is important, as it illustrates


several basic operations in SIMSCRIPT II programing. First, it
illustrates the use of a set pointer to select a set member; F.ROUTING
(JOB) picks out an entity identification number. This identification
number is then used with an attribute of the entity type it represents
(OPERATION) to determine a value; MACHINE.DESTINED(F.ROUTING(JOB)) is
the number of the production center required by the first operation.
This number is assigned to PRODUCTION.CENTER so that implied sub-
scripting can be used later on in the program. The statement could
have been written as: LET PRODUCTION.CENTER-MACHINE.DESTINED(F'.ROUTING),
as JOB could be implied.
After the production center is determined, NUMBER.IDLE(PRODUCTION.
CENTER) is examined to determine if a machine is available in this
production center to process the job. If a machine is available, it
is allocated to the job by first subtracting 1 from the idle-machine
counter and then calling the routine ALLOCATION. If a machine is not
available, the job is filed in a QUEUE that is owned by the production
center. When a machine becomes free at sme later date, the QUEUE
will be examined and a job removed for processing. All the time a
job spends in the shop in excess of its actual processing time is
spent in queues belonging to different production centers and in
finished goods inventory.
ALLOCATION know* that it is given a certain JOB by the fact that
the identification number of this JOB ib in the global variable JOB.
It removes the first operation from the ROUTING of this JOB, and
schedules an END.OF.PROCESS event to occur. The identification and
the production center identification are assigned to the first two
attributes of this event notice. The event is scheduled for a
standard time in .he future. PROCESS.TIIE(OPERATION). modified by a
factor that depends upon the current time and the time the ;ob was
promised to the customer. Note the use of implied subscripts in
-355-

communicating between the routines ALLOCATION and EXPEDITE.FACTOR,


and within the routines themselves.
EXPEDITE.FACTOR looks at the DUE.DATE of the current JOB and
compares it with the current simulation time. If the job is late,
EXPEDITE.FACTOR returns a value of 0.5 to shorter the processing time
of the operation. If the job is not late, a value between 0 and 1 is
computed, which depends upon the time remaining before the Job will
be late and the processing time of the current operation. Again,
implied subscripts are eoployed.
The event END.OF.PROCESS does two things: it takes care of the
JOb that han just finished processing at a production center, and it
takes care of the production center. First it seals with the job.
If the ROUTING of the job is empty, all its operations have been per-
formed and it can pass from the shop. If the job is finished on time,
or is late, its entity record is destroyed imediately. If it is
early, it is filed in FINISHED.GOODS.INVENTORY where it stays until
its DUE.DATE. If the job is not completed, the routine ATTEND.TO.JOB
assigns it to its next operation. Note the use of the REMIVE state-
ment in ALLOCATION that makes this assignment automatic.
It Is important at this point to understand the flow of control
between events and routines. The reader is advised to make up some
data, or use the data at the end of the program and trace through
several jobs and their flow through the shop.
After disposing of the Jb, END.OF.PROCESS deals with the pro-
duction center. If no jobs are awaiting processing in its QUEUE, the
machine just released is returned to the Idle state. If jobs are
waiting, one is selected according to the queue's priority rule and
processing started on it.
This completes the routines and events that are directly involved
in the shop simulation. The retaining routines and events deal vith
preparing reports, stopping the simulation, collecting data, and
monitoring the model.

1VES AND ROUTINES FOR M KITORINC, DUGGING, AND ANALYSIS

The event WEEKLY.REPORT occurs paricically. It koeps track of


-356-

the number of simulated weeks that have gone by, resets counters that
are used for collecting periodic statistical information, calls on a
report routine, and reschedules itself. The feature of interest in
this routirne is the use of the word WEEK in the RESCHEDULE statement.
This word was defined to mean *HOIJRS.V*7 HOURS in the program preamble;
the RESCHEDULE statement is therefore compiled as RESCHEDULE THIS
WEEKLY.REPORT IN 1*HOURS.V*7 HOURS. When declarations such as this
are made, care must be taken that the defined word is not used inad-
vertently in another context; e.g., there can be no variable, routine,
label, or set named WEEK in this program.
The event END.OF.SIMULATION is triggered externally. Its only
purpose is to terminate a simulation run, which it does by emptying
the events sets so control will iass to the statement after START
SIMULATION when END.Ov.SIMULATION returns control. In addition to
stopping the simulation, END.OF.SIWILATION calls REPORT and lists an
array.
The next two routines, QUEUE.CHECK and STAY.TIME, are associated
with the BEFORE statements of the preamble. QUEUE.CHECK is called
before filing or removing is done in any QUEUE; STAI.TIME is called
before any JOB is destroyed. The sole purpose of QUEUE.CHECK in
error checking; its code is straightforward. STAY.TIME has a dif-
ferent purpose. It computes the time a JOB spends in the shop,
"assigning this time to a variable for which a TALLY operation has
been specified. Note that STAY is used to compute statistics through
its TALLY computations, but as it is not used anywhere else in the
program, is declared DUMMY and given no storage location.
TRACE is more complicated. Triggered by a call from BETWEEN.V
before every event, it i4 used for event tracing and for releesing
Jobs from finished goods inventory when the simulation clocK reaches
their due date. The first part of the routine deals with this task.
The code sakes use of the fact that Jobs are ranked in FINISHED.GOODS.
INVENTORY in order of their DUE.DATE to make the search more efficient.
The trace section of the program :-as EVENT.V to branch to a
different output statement according to the type of event that has
been selected to occur next. These output statem.nts print different
-357-

items of information about each event type. The program could as


easily be written to take actions on the event types, such as turning
off the trace by setting BETWEEN.V=O when TIME.V reaches a certain
value or a special kind of event occurs.
Routine NUMBER.IDLE is a left-handed routine that implements the
monitoring of the attribute NUMBER.IDLE. It has several unusual
features. One reason for defining NUMBER. IDLE as a left-hand monitored
variable is to enable the programmer to save values of the number of
machines idle over time for later processing, without putting the code
to do this in the simulation routines. If at some later date the
programmer wants to remove this feature from the program, he need only
remove the preamble card that states that NUMBER.IDLE is monitored
and the routine NUMBER.IDLE, and recompile the program. No changes
need be made to any other routines.
The program uses two SAVED local arrays to collect and write on
tape successive values of NUMBER.IDLE for each of the production cen-
ters. A global variable TAPE.FLAG is used to tell the routine when
initialization of the SAVED local variables is required; TAPE.FLAG
is set to zero at the start of every simulation experiment. The pro-
gram puts successive files of arrays on tape. Each file contains
data for a different experiment. The routine demonstrates SAVED
variables, local arrays, a left-handed function, subscripted sub-
scripts, and monitcred varia -s.
The last routines deal th reports of system activity during
a simulation experiment. They print out the parameters of the experi-
ment and the measurements made during the experiment. They illustrate
the report-generating facilities of SINSCRIPT II as well as the
COMPUTE statement.

5-06 VISCELLA4.Y'C,.S S;r.ILA7ION ToPrCS

Event Tracing and Monitorin-

Statistics obtained thro,.4h TALLY and ACCUMULATE statemnts


reveal aggregate properties of a model, but say little About the way
it responds in particular situations. When checking out a model, it
-358-

is important that all aspects of system dynamics be verified; given


a situation, what events are generated to resolve it; given a system
state, what events are executed in pass'ag from it to another .tate.
Unless output statements are incorporated into every event rou-
tines, it is impossible to trace system dynamics completely. BEFORE
and AFTER statements are useful but inadequate as a sole source of
tracing ability. What is wanted is an entry to the timing rout:ine
that allows selected information to be output before each event is
executed.
The SUBPROGRAM system variable BETWEEN.V is provided for this
purpose. The timing routine contains the statements

IF BETWEEN.V IS NOT ZERO, CALL BETWEEN.V


REGARDLESS....

inmediately before the statements that branch to the selected "next"


event routines. After a ne;r event selection has been made, and
before the event routine is called, BETWEEN.V is examined to see if
tracing is to be done. At the start of every simulation the system
sets BETWEEN.V to zero: unless the programmer assigns a routine nm
to it, events are executed one after another without interruption.
A global variable named EVENT.V makea selective tracing possible.
After che timing mechanism selects an event notice and sets TIME.V
to its TIM..A attribute, EVENT.V is set to a code number representing
the class of event that has been chosen. These codes are integers
from 1 to E..'ENTS.V; they are assigned in two ways: (1) events appear-
ing in a PRIORITY statement are numbered 1,2,...,N in the order in
which they are listed, and (2) events not appearing in a PRIORITY
statement are numbered in the order in which they appear in a prLamble.
If some events appear in a PRIORITY statement and se do not. nu-
bering starts with those events in the PRIORITY statement and contin.es
with the remaining events. The code assigned to a particular event
is stored in the global variable 1.#twn.
EVENT.V is most conveniently used in a computed GO TO statement.
directing control to statemnts that ere relevant to the event type
just selected. The following exaWle illustrates how a tractng routine
s wTritten:
-359-

PREAMBLE
EVENT NOTICES.... INCLUDE ARRIVAL AND SALE
EVERY END.OF.PROCESS HAS A TIME AND A WHO.COWPLETED
EVERY SHIFT.CHANGE HAS A PERIOD.NUMBER
PRIORITY ORDER IS SALE, SHIFT.CHANGE AND ARRIVAL

etc.

END

MAIN
NOW INITIALIZE
LET BETWEEN.V-'TRACE'
START SIMULATION
STOP END

ROUTINE TO TRACE
GO TO SALE, SHIFT.CHANGE, ARRIVAL OR END.OF.PROCESS
PER EVENT.V
'SALE' WRITE TIME.V AS "SALE OCCURRED AT ",D(10,4),/
RETURN
'SHIFT.CHANGE' WRITE TIME.V PERIOD.NUMBER AS "SHIFT CHA?'GE OCCURRED',
"AT ",D(10,4)," FOR PERIOD ", I 4,/
RETUR14
'ARRIVAL: WRITE TIME.V AS "ARRIVAL OCCURRED AT ",D(10,4),/
RETURN
'END.OF.PROCESS' WRITE TIME.V, TIME AND WHO.COMPLETED AS -END OF%,
"PROCESS OCCURRED AT ",D(1O,4),"JOB TOOK ",D(5.1'1
"TIME UNITS A*:; WAS COMPLETED BY MAN NO. ",I 4,/
RETURN
END

The key items to notice about this program are:

EVENT.V is an INTEGER variable that the timing routine sets to


a code representing the type of event about to be executed.
TIME.V is a REAL variable that is the simulated time the event
about ') be executed is to occur.

A global variable having the same name as the eveat type selected
contains the identification number of the selected event notice.
This permits implied subscripts to be used in the trace routine.

A prograser can check for a particular event by using :he I.erwnk

variables. a in:
-360-

ROUTINE TO TRACE
IF EVENT.V a I.ARRIVAL,
WRITE TIME.V AS "ARRIVAL AT ",D(10,4),/
ELSE
RETURN END

BETWEEN.V can also be used to turn BEFORE and AFTER traces on


and off. Either programmed conditions or events can be used. The
folloving program illustrates this.

PREAMBLE
TEMPORARY ENTITIES...
EVERY DOG BELONGS TO SOME KENNEL
PER:.,IENmr ENTITIES...
EVERY FARM OWNS A KENNEL
EVENT NOTICES...
EVERY SALE HAS A PRICE AND A DOG.NUMBER
EXTERNAL EVENTS ARE SIGNAL AND END.OF.SIMULATION
DEFINE PROGRAM AS A SUBPROGRAM VARIABLE
BEFORE FILING IN KENNEL, CALL PROGRAM
END

LET PROGRAM a 'FILE.TRACE'


CALL INITIALIZATION
START SIMULATION
END

EVENT SIGNAL
READ CODE IF CODE - 1. LFT PROGRAM - 0 RETURN ELSE
IF BETWEEN.V - 0, LET BETNEEN.V - 'TRACE'
RETURN
ELSE LET BETWEEN.V - 0 RETURN
END

ROUTINE TO TRACE
PRINT 1 LINE WITH EYENT.V AND TIME.V THUS
EVENT TYPE *'* EXECUTED AT TIME *''*
RETURN
END

ROUTINE FOR FILE.TRACE GIVEN ENTITY AND SUB


DEFUIE ENTITY AMD SUB AS INTEGER VARIABKES
WRITE SUB AS "DOG PUT IN KENNEL(',I 2.')',i
RETURN END

The system pr*vides another kind of trace facility through a


TRACE etatement. When us.d, :ths statesent displays the mewvry loca-
tion the statement vas executed fro., and the locations of all higher-
level routine calls currently in effect. The TRACE statent thus
-361-

provides a dynamic map of the function and procedure call3 that are
in effect when it is executed. The output of TRACE looks like:

AT LOCATION ******
CALLED FROM ******
CALLED FROM ******

CALLED FROM ******

The AT LOCATION line displays the memory location of the objeýr pro-
gram statement that called TRACE. The first CALLED FROM line displays
the memory location of the object program statement that called the
routine that called TRACE. knd so on. If TRACE is executed in a main
routine, no CALLED FROM lines appear.
A programer cAn identify the source program statements that
correspond to displayed memory locations from the memory map and
assembly listings that are part of the normal SIMSrRIPT IT compiler
output. Since computer systems generate maps and listings in dif-
ferent formats, it is impossible to dipcuss how one does this here.
The following program uses symbolic names raLher than memory locations
to illustrate TRACE; SI.SCRIPT II implementation manuals give more
explicit infoimation.
Example of the use of TRACE:

PREAMBLE
NORMALLY MODE IS REAL
DEFINE COMPUTE AS A REAL FUNCTION
END

MAIN
READ X, Y AND Z AS 3 D(10.3) USING UNIT 6
"1 CALL CALCULATE GIVING X, v AND Z YIELDING Q
LIST X. Y. &IAND Q
STOP END

ROUTINE TO CALCULATE GIVEN, A, 8, AND C YILL)ING D


IF A 8+.C, LET D-A RETh'RN FLSE
IF A 8, LET D-A-B RETURN ELSF
IF A C. LET D-A-C RETURN ELSE
T LET D-COPUTE(A, ;. Cý
RETURN END
------------------------ - -- ---- --
-- -- -- -- -- ----
-362-

ROUTINE TO COMPUTE(E, F, G)
IF G IS NEGATIVE,
13 TRACE
WRITE E, F, G AS /, B 10, "AN ERROR WAS FOUND, THE",
"DATA IS", 3 D(5,1).
STOP
ELSE RETURN WITH SQRT.F(E**2+F**2+G**2)
END

Given as data the numbers -10, 10, and -5, this program produces
the display

AT LOCATION r13
CALLED FROM w2
CALLED FROM w11
AN ERROR K"AS FOUND, THE DATA IS -10.0 10.0 -5.0
By tracing through the memory locations, a programmer can ace
that the error was found at 13 -" in routine COMPUTE, called from w2 --

in routine CALCULATE, called from w, -- in the main rroutine. Each of


the w, rin be traced to a source program statemer.t. The flow of the
program can be reconstructed and the source of the error exposed.
The reader should go through the examples in previous sections and
attempt to use TRACE wherever he feels it is applicable.
TRACE Is also used by the SINSCRIPT II system when a syster. error
is found, such n, an attempt to real a decimal number into an INTEGER
variable. The information produced b7 the trace display enables a
programmer to locate errors in his source program, although both he
and the system may have gone through several levels of calls before
the error was found ard flagged.
TRACE uses the current output unit. If a program finds an errcr
while a tape, disk, or drum is current, a printer should be specified
before TRACE is called. Assume that unit 3 is the standard output
unit, a printer. A safe statement for using TRACE is:

TRACE USING 3

When the system calls TRACE, it automatically sets the szandard out-
put device as the current output unit and restores the unit that was
current when the trace is completed.
-363-

Synchronous Variables

Certain simulations can suffer from what is called "parallel


interaction," two events happening at the same time that affect one
another. A simple example of this can be seen in the situation where
two events examine and possibly modify the same variable. Since the
events are executed serially, though with the same 7IME.V, the event
that occurs first can modify the variable so tiat the value seen by
the second event is not the one it should be seeing. The problem is
one of synchronization, of getting -rriables to change value, not
necessarily when assignments are made, but when simulated time increases.
In programs where it ie necessary te account for parallel inter-
actions, it is possible tc do sc by using a left-hand monitored array
and the BEIWEEN.V mcchanism. The following example illustrates how
"syik..ronous variables" can be defined and used:

PREAMBLE
THE SYSTEM OWNS A SYNCH.SET
TEMPORARY ENTITIES...
EVERY MEMO HAS A VALUE AND A SUB AND BELONGS
TO THE SYNCH.SET
DEFINE SUB AS AN INTEGER VARIABLE
DEFINE X AS A REAL, I-DIMENSIONAL ARRAY MONITORED
ON THE LEFT
END

1MAIN
LET BETWEEN.V='SYNCH'
START SIMULATION
STOP END
----------------
------------------------------- -- -- -- -- -- ----
ROUTINE SYNCH
j DEFINE TAS AREAL, SAVED VARIABLE
IF T = TIME.V, RETURN
OTHERWISE
LET T = TIME.V
FOR EACH MEMO IN SYNCH.SET, DO
REMOVE MEMO FROM SYNCH.SET
LET X(SUB) = VALUE
DESTROY MEMO
LOOP
RETURN END
---------------
------ --- ------ --------------
-- -- -- -- ---- --
-364-

LEFT ROUTINE X(J)


DEFINE J AS AN INTEGER VARIABLE
ENTER WITH A
CREATE A MEMO
FILE MEM40 IN SYNCH.SET
LET SUB-J
LET VALUE-A
RETURN END
In a program containing these definitions and routines, the value
of an element of X is changed only when simulated time advances. A
statement such as LET X(5) - X(5) + I within an event does not change
the value of X(5) until simulated time advances.
The routine for X can be used as a prototype for all synchronous
variables. Only the number of subscripts and mode need be changed
for other situations. The SYNCH routine can be used as is, or incor-
porated into a more extensive "BETWEEN.V" routine.

Activity Scanning

Event achedu~ing is one of several methods of controlling system


dynamics. Other computer simulation languages, such as GSP, CSL, and
SIMULA, are based cn activity acanning and process control.
The concept of activity scanning is easily incorporated in a
SIMSCRIPT II simulation through the BETWEEN.V mechanism. The follow-
ing program shows how this can be done. Since implementation is up
to the programmer, any degree of sophistication required is available.
It is possible to program a simulation using pure event sequencing,
pure activity scanning, or a mixture of both.
Consider a shop in which a man and a machine must work together
to produce some products, the man can work alone to produce others.
and the machine can work alone to produce others. The basic element
of interest is the multiresource nature of the problem and how it is
handled by activity scanning. To emphasize this aspect, all other
facets of the problem are simplified.
-365-

PREAMBLE -6
PERMANENT ENTITIES....
EVERY MACHINE HAS A STATUS, A CLOCK AND A PROCESSING.TIME
EVERY MAN HAS A CONDITION. A WATCH AND A WORK.TIME
THE SYSTEM OWNS A QUEUE
EVENT NOTICES INCLUDE STATE.CHANGE
EVERY SALE HAS A CODE AND MAY BELONG TO THE QUEUE
DEFINE CODE, STATUS AND CONCITION, AS INTEGER VARIABLES
PRIORITY ORDER IS STATE.CHANGE AND SALE
END

MAIN
READ N.MACHINE AND N.MAN
CREATE EVERY MACHINE AND MAN "INITIAL CONDITIONS ALL ZERO
SCHEDULE A SALE AT 0.0
LET CODE - UNIFORM.F(1.0,3.0,1)
LET BETWEEN.V-'ACTIVITY.SCAN'
START SIMULATION
STOP END

EVENT SALE GIVEN CODE-SAVING THE EVENT NOTICE


DEFINE CODE AS AN INTEGER VARIABLE
FILE THIS SALE IN THE QUEUE
SCHEDULE A SALE AT TIME.V+O.5
LET CODE - UNIFORM.F(O.O,3.0,1)
RETURN END

EVENT STATE.CHANGE
RETURN END

ROUTINE FOR ACTIVITY.SCAN


DEFINE MAN.CODE, MACHINE.CODE AND BOTH.CODE AS INTEGER VARIABLES
FOR EACH MAN, WITH WATCH-TIME.V, DO LET CONDITION-O
LET WATCH-RINF.C
LOOP
FOR EACH MACHINE. WIFH CLOCK-TIME.V, DO LET STATUS-O
LET CLOCK-RINF.C
LOOP
UNTIL QUEUE IS EMPTY OR (MAN.CODE-1 AND MACHINE.CODE-1 AND
BOTH.CODE-I). DO
REMOVE THE FIRST SALE FROM THE QUEUE
GO TO MAN OR MACHINE OR BOTH PER CODE
'MAN' FOR EACH MAN WITH CONDITION-O, FIND THE FIRST CASE
IF NONE
'FAILURE' LET MAN.CODE-1 FILE THE SALE IN THE QUEUE GO TO LOOP
ELSE LET CONDITION-1 LET WATCH-TIME.V+WORK.TIME
'DONE' DESTROY THE SALE GO TO LOOP
'MACHINE' FOR EACH MACHINE WITH STATUS-O, FIND THE FIRST CASE
IF NONE,
LET MACHINE.CODE-1 GO TO FAILURE
ELSE LET STATUS-I LET CLOC.-TIME.V+PROCESSING.TIME
GO TO DONE
-366-

'BOTH' FOR EACH MAN WITH CONDITIONOD, FIND THE FIRST CASE
IF NONE,
GO AHEAD
ELSE FOR EACH MACHINE WITH STATUS=O, FIND THE FIRST CASE
IF NONE,
'AHEAD' LET BOTH.CODE-1 GO TO FAILURE
ELSE LET CONDITION,,1 LET STATUS,1
LET T-MAX.F(PRGCESSING.TIME, WORK.TIME)
LET CLOCK-T LET WATCH-T GO TO DONE
'LOOP' LOOP
FOR EACH MAN, COMPUTE T AS THE MINIMUM OF WATCH
FOR EACH MACHINE, COMPUTE S AS THE MINIMUM OF CLOCK
SCHEDULE A STATE.CHANGE AT MIN.F(T,S)
RETURN
END
The reader wll notice that this program has no output statements

and no data collection statements and is unrealistic in other ways.


One exercise a reader might unertake is conversion of the program
to a complete and meaningful simulation model,
In addition to its incompleteness, the program makes no attempts
at execute-time efficiency. A second exercise is alteration of the
program, perhaps adding events or other meehanisms, to make it execute
more efficiently.

5-07 RECAP

Many of the statements in Levels 1 through 5 are definitional.


Of the 65 different statements in these levels, 20 are definitional;
14 ca% only be used in the preamble. This section recaps these state-
ments and restates the most important rules about their use.
Table ',-el lists the statements that can appear in a preamble
and states their rules of precedence.
-367-

Table 5-11

PREAMBLE STATEMENTS

Statement
Type Statement Rules

la NOF44ALLY Can appear anywhere in preamble.


b DEFINE TO MEAN
c SUBSTITUTE
d SUPPRESS SULST.
e RESUME SUBST.
2& TEMPORARY ENTITIES A preamble may contain many Type 2a,
b PEM4ANENT ENTITIES 2b, and 2c statements. Each may be
c EVENT NOTICES followed by a group of Type 3a, 4,
and 5 statements.
3a EVERY Many can follow a Type 2 statement. An
b THE SYSTEM entity or event notice name can appear
in more than one EVERY statement.
4 DEFINE variable No precedence relation if it eefines a
global variable. Must follow all Type
3a statements if it defines an attribute
named in them. A variable. attribute.
or function name can only appear in one
DEFINE statement.
5 DEFINE set Must follow Type 4 statements in a
I Type 2 statement group.
No Type 6-9 statements can precede any Type 2-3 statements.
6a BREAK TIES One statement allow-ed for each event
b EXTERNAL EVENTS notice.
c EXTERNAL UNITS
7 PRIORITY Must follow all Type 2c and 6b statements.
8a BEFORE Allowed for each temporary entity, set
b AFTER and event notice.
9a TALLY One statement allowed for each global
b ACCUMULATE variable or attribute.

Of theot statements, only Types 1 and 4 can be used in routines

I
to declare local background conditions, variables, and substitution*.

I
-369-

Appendix

SIMSCRIPT Il SYSTEM NAMES

CONSTILSTS VARIABLES FUNCTIONS


EXP.C BETWEEN.V ABS.F
INF.C BUFFER.V ARCCOS.F
PI.C EOF.V ARCSIN.F
RAOIAN.C ARCTAN.I
RINF.C EVENT.V ATOT.F
EVENTS.V BINOMIAL.F
HOURS. V CONCAT.F
SETS LINE.V COS.F
EVSLINES.V DATE.F
EV.SMARK.V DAY.F
ENIISMINUTES.V DIM.F'
ENTIlESPAGE.V DIV.F
RANDOM. RCOLUMN.V EFIELD.F
REAM. E-RLANGF
ATTRIBLC~ES SEEO.V EXP.F
ENTATIME.V EXPONENTIAL.F
EUTAM WCOLUWI.V FHAC.F
IVALUE.A WRITE.V CIAW~.F
LENGTH. A INR.F
M.EV.S ISTEPJ
PROM. ISTOA.F
P.EV.S LIN.F
RVALUE.A LOG.E.
TIME.S LOG.NORMAL. F
LOG. 1O.F
ROUTINES mIN.F
ORIGIN.R MINUTE.F
MOM.
MONTH. F
NORMAL. F
POISSON .
RANDOM.F
RE AL. F

SFIELO.
SIGII.F
SIN.F
SQRT.F
TANJ
TRUNC.F
TTOA.F
L0R4 IFORM. F
a ~WEE'MAY:F
YEAR. F
-369-

Appendix

SIMSCRIPT 11 SYSTEM NAMESJ

CONSTANTS VARIABLES FUJNC'TIONS


EXP.C BETWEEN.V ABS.F
INF.C BUFFER.V ARCCOS.F
PI.C EOF.V ARCSIN.F
RADIAN.C EETVARCTAN.F
RINFC EVNT.VATOT.F
RIN.CEVENTSOV BINOMIAL.F
HOURS.V CONCAT.F
SETS LINE.V COS.
LINES.V DATE.F
EV.SMARK.V DAY.F
ENIIE INUTES.V DIM.F
ENTIIESPAGE.V DIV.F
RANDOMA. RCOL"W44 EFIELD.F
READ.V ERLANG.F
A.TrRIBTB~ES SEED.V EXP.F
ENTATIME.V EXPONENTIAL.F
EUNIT.A WCOLUPI.V FRAC.F
~VALE.AWRITE.V GAMMA.
LENGTH.A HOUR.
MROB.A ISTEP. F
PRO.AI TOA.
P.EV.S I.
RVALUE.A LOG.E.

TIME. A LOG.NORMAL.F
LOG. 1O.Ft
ROUTINES MIN.F
ORIGIN.R P4INIJTE.F
MOM.
MONT H .F
NOWKL.FI
POISSON.F
RA.NDOM.F
RE AL. F
RSTEP.F
SFUELD. F
SIGNJ.
SIN.F
SORT. F
TAX.F
TRUJNC.F
TTOA.F
LR41FSR.F
WEEKA. F
WE BULL. F
YEAR.
-371-

INDEX

NOTE: The letter 'n' following a page


reference indicates a footnote.
The letter 't' following a page refer-
ence indicates tabular material.
Imbedded periods have been ignored for
alphabetizing purposes.

A format, 162 AND (continued):


ABS.F function, 91t, 369t logical operator, 135
Absolute time specification, 301 prohibited keyword, 29n
ACCUMULATE statement, 324 Antithetic variate, 313
computations, 329t ARCCOS.F function, 91t, 369t
defined, 328
DUMMY variable, 335f. ARCSIN.F function, 91t, 369,
example, 339-340, 349
initialization of counters, 332f. ARCTANF function, 91t, 369t
Action taken when no events, 294 Argument, 84
Activity-. array pointers, 103-104
defined, 28declaration of correct number, 95, 101
defined, 282 defined, 90
scanning, 364 of an event notice, 311
time genaration. 313 input, 92f., 95
ADD statement, 9f. list, 84
ADVANCE statement, 173 output:
of a function, 93-94
A.EV.S routine, 295 of a routine, lOf.
AFTER phrase (time specification), 301 variable number of, 9J
AFTER statement (debugging): Arithmetic:
arguments, 323t expression, 2; see also Operator, arithmetic
defined, 322f. Array:
Allocate storage, 37 declared, 36f.
eoe also CREATE statement; RESERVE statement defined, 33-37
ALPHA-
attribute, 208 initialization, 39
in LIST statement, 73f.
example, 328 mixed mode, 63f.
format descriptor (A), 162 mode, 35
function, 151
lfteral. 151f. pointers:
defined, 54-59
todedefined, 15rf. as routine arguments, 103
variable: in PRINT statement, 48
declared, 151 processing efficiency, 64
in expressions, 151 READ:
in free-form READ, 152 controlled. 54f.
in LIST statement, 153 froe-form, 48f.
in PRINT statement. 153 reference, 34
specification rules for attributes, 221
ALSO FOR statement, 133 storage:
ALWAYS statement, 14; aee also ELSE statement compression, 218-220
Analysis of results, 324; see also ACCLUMLATE release,37,11054-59
usual,
statement; TALLY statement structures, 5-,
AND: ragged table, 58-64
coma, 6 use, 40-44
-372-

AS BINARY phrase, 115f. Basic symbolic units, 10


AS FOLLOWS phrase, 17 BEFORE &tatement (debugging):
arguments, 323t
A.009 routine, 258t defined, 323
Assignment: example, 339, 349
of attributes, 219 BEGIN HEADING statement. 181
operator (-). 9
of values: BEGIN REPORT statement, 179
by LET statement, 6f. Behaior of a system, 282
by READ statement, 9f.
without conversion, 279f. BELONG TO clause, 200
Assumed mode. 30 RETWEEN.V system variulple, 358. 369t
example, 350
(*):
Asterisk
format, 168 Binary:
in PRINT statement, 18 ext-rnal event data, 309
in RELEASE statement, 11Off. input/output, 175f.
in RESERVE statement, 37ff., 54ff. Binary operators, 3; ac also Operator
used in a subscript position, 58ff.
se. also MARK.V system variable BINOMIAL.F function, 314, 369t
AT phrase, 298, 300 Bit packing, 212
AT LOCATION line, 361 Planks:
when required, 11
Body o a subr o r, 83
ATOT.F function, 276, 369t
At.,futoiBody of a subprogram, 83
At.-$butet
comen,'. 195, 220 Branching, see T7ansfer
counter, 224 BREAK TIES statement:
defined, 194 defined, 290
dimension, 208f. example, 339
of entities, 195 prohibited use of, 293
permanent, 204
temporary, 203 Bseet routine, 258
equivalenre, Zlltf. Buffer:
of event notice, 288 defined, 156
example, 254, 338t, 348 internal, 178
as functions, 222f. use of, 176ff.
membership, 224
mode, 208f. THE BUFFER, 178
name clause, 200t BUFFER.V system variable, 178, 369t
nar•ing convention, 195
optional, 254
output, 246
through LIST statement, 247 C format, 162
packing, 211ff. Calendar tine:
reference, 194 Conversion:
nested, 228 conversion functions, 3020, 3070
of permanent entity, 205 defined, 301-302
of temporary entity, 203 format, 305
relitive location, 195 origin, 306
of a set, 196f. CALLED FROM line, 361
deletion of, 234 CALL statement, 100
spPcification to word or array, 221
if the system: Called eubprog,'a, 79
progr&mmer-defined, 207 Calling subprvgram, 79
system-defined, 369t
of the timing routine, 294ff. CANCEL statement:
defined, 303f.
AVERAGE statistic: used in BEFORE and AFTER statements, 323t
ACCUMULATE statement, 37)t
COMPUTE statement, 149L CAUSE statement:
TALLY statement, 321t defined, 298
used in BEFORE and AFTER statements, 323t
oee alio Scheduling
B format, 167 C.entity routine, 295
BACK FROM clause, 173 Character string:
Background conditions, 30; see NORMALLY statement ALPHA. 150
BACKSPACE statement, 173 TEXT, 272
output forlmat (" ,168
Base pointer: Class:
defined, 54-56 of entities, 194, 196
symbol, 54 symbo, 54of events, 286
shorthand notation, 66
ore aoio Pointer CLOSE statement, 173f.
-373-

Column repetition, 185 Current (ft'tinuod}:


unit, 154
Coma, 6 outpu.
vhen required, 11, 201, 233 buifer, 177
Comment. 12 pointer, 177
positioning. 167
Comon: unit, 154
attributes, 195. 220
sets, 220 sets,220D format, 159
134
complex logical exronsions,
Data:
Compound: card for external event, 287
entities: collection, 324
example, 348 editing:
mixed, 244 internal, 178f.
permanent, 242 through monitored variables, 264
temporary, 244 for external event, 304ff.
expressio!'s: field, 8n, 156
arithmet.c, 3 formats, nee Format
logical, 134 for free-form READ, 7, 156
Compression of array storage, 218 input conversion, 32t
look-ahead properties, 77t
COMPUTE statement: for random va'iables, 320
defined, 147 record, 156
list, 11.7 stream, 156
possible statistical names, 149t structure, 156
remote use, 148
OATE.F function, 307t, 369t
Computed GO TO statement, 66
OAY.F function, 307t, 369t
Computer language, 1
Computer program, 1 Day-hour-minute format, 305
DAYS phrase,
301
Concatenation of TEXT, 273
Debugging, 322ff., 357ff.
CONCAT.F function, 273, 369t eaealeo AFTER statement
Constant: BEFORE statement
defined, 2, 28 BETWEEN.V system variable
restriction to size, II TRACE statement
of the system, 369t Decimal:
Continuous time simulation, 283 format descriptor (D), 159
number, 2, 30
Control: point:
:ards foi overlay, 143
in 0 format, 150
phras.,, jce For phrases in E format, 160

Controlleo statement, 4A print conventions, 19t


18f. time units forEaL, 305
Contiguous values in PRINT statement, Bee aloo REAL
Conversion: Declaration:
of expressionL, 31ff. of attributes:
functions: common, 195, 220
mode, 276t
time,302t,307tof an entity, 195208f.
dimensionality,
time, 302t. 307t
of ianen ce, 195
of input data, 32t
320 equivalence, 211f,
for RANDOM probability values
as a function. 222, 241
of output data, 19t, 161 mode, 20Sf.
COS.F function, 91t, 369t packing, 211ff.
of THE Si;TEM, 207f.
Counter attribute, 224 of entities, 195
CREATE statement: compoutd, 242
for eaopound entities, 243 permanent, 204
example, 254 temporary, 201
fnr permanent entities, 201 of event, 287
for temporary entities, 204 of event notice, 288f.
used in BEFORE and AFTER statements, 323t of external event, 292
of function, 93
C.Set routine, 258 arguments, 95
CSL simulation language, 364 DYNAMIC, 144 260
left-handed,
Cumulative: RELEASABLE, 141
probabilities for sampling, 320 of set. 196, 224ff.
statistics, 333 compound, 243
Current: ranked, 233f.
Input: WITHOUT:
pointer, III attribute, 234
positioning, 167 routines, 259
-374-

Declaration (continuod): Distinct labels, 67


of variable. DIV.F 'unctior, 91t, 369t
dimension, 35fD.
DUMMY. 335f. DO statement:
mode: defined, 51
ALPHA, 151 nested, 53
numeric, 30 simplified by ALSO FOR statement, 132f.
TEXT, 272f. D."t rot-ne. 258
MONITORED, 262f.
RANDOM, 316 OUPI4Y:
SUBPROGRAM, 267 declaration, 335
type, 115 example, 349
aes also DEFINE statement; EVERY statement used with TALLI and ACCUMULATE statement., 335f.
DEFINE statement: Duration of an activity, 283
DIMENSION, 36f. Dynamic storaae allocation:
DU4fI, 335 for arrays:
FUNCTION, 93 for arrays:
arguments: RELEASE, 1101.
input, 91 RESERVE, 37
output, 100 R 333
DYNAMIC, 144 RESET, 333
RELEASABLE, 141 for routi.es:
mode: defined, 144
ALPHA, 151 overlay, 142fl.
numeric, 30 RELEASE, 140
TEXT, 272f. for temporary entities:
MONITORED, 262 CREATE, 201f.
RANDOM, 317ff. DESTROY, 204
set: Dynamic structure, 339
ranked, 233
WITHOUT: Dynamics of a .ystem, 282, 293f.
attributes, 234
routines, 259
SUBPROGRAM, 267
type: E format, 160
RECURSIVE, 115
SAVED, 115 Editing:
input information, 76f.
DEFINE TO MEAN statement: internal, 178f.
defined, 120 output information, 177f.
example. 173, 339, 356
scope, 121 EFIELD.F function, 77t, 91t, 369t
Deletion: Element of an array, 33
of array, 110 ELSE statement:
of entities: defined, 14
permanent, 206 elimination of, 131f.
temporsayt 204 nested, 16
of event notice, 303f.
of routine, 14C End-of-file:
of set: condition, 174
a ttributes, 234 check statement, 174
routines, 257-259 marker, 173
of TEXT, 274 End of simulation, 356
D'ESTROY stAtement: END statement,
defined, 204 used to physically terminate:
example, 254 hzading section, 181
used with BEFORE ani AFTER statements, 323t preamble, 30
Der:cc nams, 154 program, 21
report section, 179
rictionary of TFXT: subprogram, 83
i;ýind, 272, 274
deietion from, 214 Endogenous event, 286; see oalo Internal event
inclusion in, 273f. ENTER WITH statement, 261
DIM.F function, 66, 91t, 369t Entity:
Dimension: common attributes, 195, 220
of an errqy: control phrase, 236ff.
declarAtion, 35 declaration, 195
defined, 33 defined, 194
frozen, 3( example, 371
incorrect number, 39f. identification number, 202
of attribute, 209t index, 195, 205
naming conventions, 195
Discrete-event simulation, 281 owner, 196
-375-

Entity (continuad): Event notice (continued):


permanent: defined, 287f.
creation, 201 by INCLUDE phrase. 288f.
declaration, 204 example, 349
defined, 204 for external event, 292, 304
deletion, 206 6lobal variable, 310
global variable, 206f. for Internal event, 288
record, 195 priority, 290f., 293
logical, 196f. SAVING clause, 311
reference, 194 scheduling, see Scheduling
nested, 228 statement, 288
permanent, 205
permpneny, 203
temporary, 203 EVENTS.V system variable, 294, 369t
-set relationship, 196f. EVENT.V system variable, 256, 358, 369t
declaration, 200t EVERY szatement:
of the system, 369 clauses used in, 200
temporary: defines:
creation, 201 attribute, 195, 208f.
declarftion, 201 assignment to words and arrays, 219, 221
deletion, 204 coemon, 195, 220
global variable, 202 DU"Y, 336
function, 201, 209
EOF.V system variable, 369t rules, 222
defined, 174 class of objects, 194
example, 351 data structure, 201
Equivalent: event notice, 288
attributesn 212 packing and equivalence:
labels, 67 permanent, 215, 218
labels, 6t s system, 216, 218
specificatione. 221t temporary, 213
ERASE statement, 274 permanent entity, 204
ERLANG.F function, 314t, 369t set, 196
global variable, 206f.
EUNIT.A attribute, 288, 369t temporary entity, 200
e-tternal event record, 292, 304 form, 195, 200
internal event record, Z99 EV.S set, 369t
Event: external event, 292
attributes, 299 internal event, 288
classes, 286 use by timing routine, 293ff.
codes, 358 EXCEPT WHEN phrase, 138
control, 296
data card, 304 Exogenous event, 286; see also -.Aternal event
format, 305 EXPC system constant, 79t, 369t
declaration. 287
defined, 282 EXP.F function, 91t, 369t
example, 339 EXPONENTIAL.F function, 314t, 369t
external, see External event
internal, see lnternal event Expression:
notice, see Event notice arithmetic, 2f.
occurrence, 285 compound, 3
priority, 291, 293 evaluation with functions, 89f.
processing, 310 logical, 5, 75
routine, 283 complex, 134ff.
scheduling, see Scheduling mixed mode, 31f.
simultaneous, 284 simple, 3
ties, 290 time, 298
time format:
calendar, 305 External event:
day-hour-minute, 305 attributes, 292
decimal 357
tracing, time units, 305 binary data, 287,
data cards, 309 292
trigger, 292, 304
format, 305
definition, 287 location of current input pointer, 307f.
dexampln3287 pre-positioning, 308
exaumple. 352 declaration, 292
EVENT IS phrase, 287f. defined. 286. 292
Event notice: event uotice, 292
arguments, 311, 312 example, 349
argumntsprocessing, 310
attributes. 288 unit, 292
manipulation rules, 299 unit, 292
programmer-defined, 299f. dclaration, 292
system-defined, 288 WXTERNAL EVENTS ARE statement, 292
declaration, 288f. EXTERNAL EVENT UNITS statement, 292
-376-

F.EV.S attribute, 369t


Free storage.
uted by timing routine, 293ff.
packing rule, 299 arrays, 110
characters trings, 274
Field:
permanent attributes, 206
defined, 156 routines, 140
Pecking, 212
in PRINT statement, temporary attributes, 204
17ff., 186ff. Frequency count, 330
suppression, 184f.
Frqn arut , 224
FIFO declaration, 234 F.ast attribute, 197, 224
Fienroution
File routines: npebattributes, Function:
generation in preamble, 257f. 222
example, 348
deletion of, 258f.
called, 93
FILE statement:
compiled in-line, 9in
AFTER, 225 conversion, 276t
BEFORE, 225 declared, 93f.
FIRST, 225 defined, 88
LAST, 225 left-handed:
used in BEFORE and AFTER statements, 323t
defined, 2v0
S~library,
FIND statement, 145
leceive 91t, 369t 260f.
value,
for RANDOM variable, 320 mode definition, 93

Forrecursve, monitoring, 113ff.


263f.
backward iteration, 46, 239
controlling DO loop, 51ff. RETURN statement, 93
THE DICTIONARY, 274 right-handed, 259f.
of the system, 369t
iteration:
FOR statement, 44 use in expression, 88
use aetributo, 32
modified: F.uaqzbZ attribute, 320
by ALSO phrase, 133
by logical phrases, 137-140, 236f.
nested, 46
for permanent entities: GAI'A.F function, 314, 369t
FOR ALL, FOR EACH or FOR EVERY statement,
236ff. Generation of activity times, 313
for sets: GIVEN clause:
FOR EACH IN "t statement, 238f.
gIVenc se:
Forbidden names, 29, 29n arguments, 95
attributes, 299f.
Format:
Global vpriables:
conventions:
automatically defined:
free-form READ, 7 event notice, 310
PRINT statement, 19t
descriptors, 157f., 172t permanent entities, 206f.
temporary entities, 202
A, 162
defined, 84, 207
B, 167
example, 86
C, 162 in recursive routines, 114
0, 159 scope, 84f.
E, 160 side effects, 112
I, 158 of the system, 369t
S, 168
T, 27 GO TO statement:
/, 168 computed2 66
", 168 defined, 13
subscripted label, 69
for ",168I
external event data, 305 A GROUP OF _ FIELDS phrase, 197
input, output, 153ff.
IN GROUPS OF e PER PAGE phrare, 185
lines, 17, 20
list, 157, 163
GSP simulation language, 364
for RANDOM variables, 320
repetition, 170
source programs, lOf., 129
HAS or HAVE clause, 20
time, 305f.
FRAC.F function, 91t, 369t
Heading section, 181
input:
Free-form: Histogram:
ACCUMULATE statement. 331
INPUT statement, 273 example, 349
see alZo•READ statement, free-form TALLY statement, 330
input data format, 7, 156
HOUR.F function, 302, 369t
output:
OUTPUT statement, 275
see alns LIST statement HOURS phrase, 301
HOURS.V system variable, 301, 369t

a,
-377-

I format, 158
Tnput (continued):
I.entity system variable, 295f., 358 free-form READ:
Identifiration number, 202
ALPHA,
array, 152
4Sf.
IF FOUND phrase, 145
controlled, 170
IF NONEphrase. 145 defined, of.
random, ?20
IF statement:
defined, 13 TEXT, 272
modified by THEN phizae, 131 INPUT, 2/3
INPUT statement, 273
nesting, 16, 131
optional coma, 16
Tnput/output:
*eaaleo IS phrases
devicei, 155
12p11od, unit characteristics, 157t
pointer aeterisks, 66
INT.F function, 91t, 276t, 369t
subscripts:
for attributes, 244 INTEGER, 2
example, 353 defined, 30
format descriptor (1), 158
in output se tatements, 246f. input conversion, 32t
for sets, 245 mode conversion, 91t, 276
IN phrases:
print conventions, 19t
ARRAY 1, 221
Internal:
DA YS , 30 1 r , 17
bnfe
THE DICTIONARY, 274
GROUPS, 185f. HOURS buffer, 178
HOURS, 301
301event, editing,28Sf.
176
definad, 286
MINUTES, 301
REVERSE ORDER, 239 example, 349
set, 232
WORD1, 219 Interpolation formula, 318
Intra packing, 212
Imbedded:
parentheses, 3 defined, 218f.
periods, 28 example, 348
IS:
INCLUDE statement:
for event notices, 289 optional use, 14
phrases:
for permanent entities, 237
ALPHA, 152
EMPTY, 232
Incremental time expression, 301
ENDED, 77
Independence of random numbers, 312
ENDOGENOUS, 286f.
Index: EXOGZNOUS, 286f.
entity, 195, 205 EXTERNAL,
of MAXIMUM, 149t FALSE, 134 287
of MINIMW4, 149t FIRST, 182
INTEGER, 77
Individual probabilities: INTERNAL, 287
for sampling, 320 LOADED, 144
INF.C constant, 79t, 369t NEW,77
Initialization: POSITIVE, is
of array, 39 REAL, 77
example, 351
of random numbers, 312 IN set, 232
by READ statement, 7 TRUE, 134
by RESET statement. 351 ZERO, 75
ISTEP.F function, 319t, 369t
routine, 351
of system activities, 294
of system state, 294 ITOA.F function, 276, 369t
IVALUE.A attribute, 320, 369t
of variables, 2
In-line function:
defined, 91n
Label:
restrictions, 141n, 267n
defined, 12
'nput:
binary, 175 local property, 87
name, 28
date conversions, 32t subscripted, 68
properties, 76, 77t
Labeled statement, 12
to a routine, b.
statements: LAST COLUMN IS statement, 129f.
formatted READ:
controlled, Last-in-set pointer, 197. 224
defined, 170 15ýff.
Leading zero supprvesioij:
TEXT, 272
in D
in I format, 159
format, 158

K
-378-

Left-handed function: MAIN:


declaration, 260 program, 80
defined, 259-262 routine example, 349
example, 357 statement, 82
used for data collection, 3;s5
used for monitoring. 264 MARK.V system variable, 369t
LEFT ROUTINE statement, 260 defined, 273
used In event data card, 305
LENGTH.A attribute, '75, 369t used in RANDOM input, 320
used in TEXT input, 273
LeTels catent,
9 2 MAXstatistic. see MAXIMUM statistic
Level of caXleg, 82
Library functions, 90, 91t, 369t MAX(e) statistic, 149t
LIFO declaration, 234 MAX.F function, 91t, 369t
MXMMsaitc
MAXIMUM statistic:
LIKE THIS phrase, 17 ACCUMULATE statement, 329t
Linear interpolation sampling, 318 COMPUTEstatement,
statement,325t149t
TALLY
LINES.V system variable, 181, 369tTALstemn,35
LINE.V system variable, 181, 369t MAXIMUM(e) statistic, 149t
LINEV syscteon,varib, 1, 3MEAN statistic, see AVERAGE statictic
LIN.F function, 3l9t, 369t MA.qAEsaitc
MEAN.SQUARE statistic:
LIST statement: ACCUMULATE statement, 329t
ALPHA, 153 COMPUTE statement, 149t
array, 73f. TALLY statement, 325t
attributes, 247
numeric, 71if. Member entity, 196
TEXT, 275 Membership attribute:
Literal: defined, 224
ALPHA, 151 used for error checking, 231f.
constant, 2 Memory allocation, 37
SUBPROGRAM, 267 see also CREATE statement; RESERVE statement
TEXT, 273 M.EV.S attribute, 369t
LOAD statement, 144 externa! event, 292
Local: internal event, 288
array: packing rule, 299
example, 106 MIN statistic, see MINIMUM statistic
RELEASE statement needed, Ill
variable: MIN(?) statistic, 149t
defined, 84f. MIN.F function. 91t, 369t
initJalization, 87
properties, 84 Minimizing storage:
RECURSIVE, 114 DUMMY in TALLY or ACCUMULATE statements, 335
SAVED, 114 equivalence, 211-222
storage, 87 packing, 211-222
LOG.E.F function, 91t, 369t see also Dynamic storage allocation
MINIMUM statiutic:
LOG.NORMAL.F function, 314t, 369t ACCUMULATE statement, 329t
LOG.1O.F function, 91t, 369t COMPUTE statement,325t
TALLY statement, 149t
Logical:
control operator, 137 mINIMUM(e) statistIc, 149t
control phasse, 137 MINUTE.F function, 302, 369t
end of program, 21
entity record, 196 MINUTES specification, 301
exprlexon: MINUTES.V system variable, 301,
complex, 134 369t
compound, 134f. Mixed mode expressions, 31f.
defined, 5 MOD. function, 9!t, 369t
simple. 5, 1f i
see also IS phrase Mode, 29
operator, 135 ALPHA, 150
Look-shoead properties: of attributes, 208
conversion:
ALPHA, 152 functions, 276
numeric, 76 of input data, 32
LOOP statement, 51 in THE BUFFER, 178
L.ast attribute, 197f., 224 of an expression., 31ff.
of a function, 93
INTEGER, 3o
Macro definition, 123 normal form, A0
Magnitude of numbers, 29 property of data, 77
REAL, 30
TEXT, 27?
-379-

Monitored variable. 262


Operator (continued):
Monitoring:
assignment, 9
of data, 264
logical:
of events, 357
defined, 135
"MONTN.F function, 307, 3691 hierarchy, 135
MOVE FROM statement, 264 relational, 5
MOVE TO statement, 263f. Optional:
asterisks, 66
M.a0 attribute, 224
attributes, 254f.
MSQ statistic, see MEAN.SQUARE statistic blanks, 4
coema, 11, 16, 30, 45
control element, 45
Name;
attribute, 195 end of coement, 12
quotation mark, 13
defined, 28
CALLED phrase, 202. 204

entity, 195 OR:


forbidden, 29, 29n in computed GO TO, 67
label, 28
length, 11 logical operator, 135
routine, 83
Order of statements:
crt, 201
variable, If. In preamble, 367t
ORIGIN.R system routine, 306, 369t
NEGATIVE phrase, 75
OTHERWISE statement, 14; see aZlo ELSE statement
N..ntiti, varIable, 205, 206 OUT. function, 369t
Nested:
neted: p defined, 177
a left-handed function, 260
control phrases, 46ff.
DO loops, 53, 132 Output:
entity reference, 228
arguments, 100
IF statement, 16, 131
correct number defined, 101
NEXT phrase, 303 of attributes, 246f.
buffer, 177
No data: from a routine, 84, 93
action taken, see End-of-file
statements:
No Notevnts:e
events: LIST statement, see LIST statement
2OUTPUT
action taken, 294 statement, 275
PRINT statement, see PRINT statament
NORAL.F function, 314t, 369t WRITE statement, see WRITE statement
Normal form, 30 of a TRACE statement, 361
NORMALLYftrme:3Overlapping packing factors, 212
NO'4ALLY statement:
dimensionality, 35f,
3verlay section, 142
mode, 30, 151, 272
OVERLAY SECT!ON CONTAINS statement, 143
scope, 85ff.
type, 115 OWNor OWNS clause, 200
Notational asterisk, 65 Ovner entity, 196
NOW:
phrase (scheduling), 30j Packing:
btatement (routine call), 100 bit, 212nf., 213t
N.-et attribute. 224 defined, 211
factor, 211
Niltstatistic, see NUMBER statistic
field, 212ff., 213t
Number: intra, 212, 218ff.
of characters in TEXT(LENGTH.A). 275
prohibited use, 299
of elements in an array (DIM.F), 66 specifications, 221
of entities in a set attribute (M.eStj, 224 PAGE IS FIRST phrase, 182
length,
lengM aiti,
11
11Page
N(MBER statistic: numbering, 182

ACCUMULATE statement, 329t PA6E.V system variable. 182, 369t


COMUTE statement, 149t
Parallel (1):
TALLY statement, 325t
in PRINT statement. !8f.
enclosing TEXT literal, 273f.
Operator: within TEXT literal, 2'4
Paralll Interactiun, 363
arithmetic:
inary, J Parameters of statistical distributions,
detined, 2f. 313
hierarchy, 4 Parentheses:
aethss
precedence rule,
4
in arittimetic expressions, 3
nry rul, 4imbedded,
unary, I J
Parentheses (continued): -8-Preambe '*ontinuedl:
In logical expressions, 135 generation of routines:
rules, 3. 42 for analysis. 325
PERFOR statement, 10 for events, 295f.
for sae.s257f.
Periodic: stateuxat, 30
reports, 333
statitics 333Precision of numbers, 29n. 75
Periods: Predecresor:
imbedded, 28f. entity. 197
terminal. 10 in-a"., pointer, 224
Permanent entities: Ple-Posirioning event data, 308
allocating storage, see CREATE statement PU!NT statement:
attribute Index. 203f. for attributes. 246
control phrases, 236ff. columan repetition, i83
"lacared, Z04f. column Suppression. l810
defined. 20l4 defined, 1)
destroying, 206 double linefi, BA
example, 348 fot.Aat cenventions, 18. 19t
globaEaibe 0f group repetition, 166 c vns

tatDE satnet,,3
204 defpultsrl, 27919
numer.
atobuf 369dtit) effeior
tyo: v~i oss 5
refteraleente
, 2 92 beithin anffevent classes: *vns
inatemnleent, 204 PRIARITYE statement, 290.29
packng ule,299default rule, 290

Physical end of program, 21 PROB -A attribute, 320. 369t


* Physical 1/0 device, 154 Probabili ties:
P!.C constant, 79t. 369t cumulative, 320
Pointer:functions, 314t
Pointer:generating, 313
for arrays: individual, 320
advantages:
arbitrary structures, 58-64 Procedure, 99; seecalso Routine
mixed mode array, 63f. Process, 364
multiple reservation,,, 60
bass, 54-56 Porm
shorthand notation, 66 defined, 1
defined, 58 overlay, 142
Initialization, 60 relocation, 143
mode, 55 Programmer, I
reference, 58
for ets:Prohibited:
comon, 220f. forms, 29
defined, 196f. word, 29n
deletion, 234 Property:
when rejuired, 241t of input data, 77t
POISSWE.F function, 314t. 369t logical, 75f.
POSITIVE phrase, 75 Pesat attribute, 197, 224
Preamble: Pseudorandom numbers, 312
allowable statements, 367t
declaring:
attribute@ of the system, 207 -'totation marks:
background conditions, as@ NORMALLY statement double quotes( )
debugging capabilities, see AFTER statement, enclosing ALPHA literal, 151
BEFORE etat ame at within ALPHA literal, 152
entities, !95. 201, 204 format descriptor, 168f.
event notices, 288 single quotes t
event priorities, see PRIOUITy statement; label, 12
BREAK TIES etaterent subprogram literal, 2681.
external event, 292 two single quites ( )
external event unit, 292 comments. M2.
global variables, 84, 207
sets, 196 RDA. osat
statistical computations, see ACCUP.LATE 9.19
R0A. o~at 9*19
statement; TALLY statement Ragged table:
defined. X4 defined, WS.
example, 140 example, 152
-381-

Random: RECURSIVE:
number: routines, 113f.
defined, 312 global variable, 114
function (RANDOM.F), 312 local variable, 114
argument, 312 variables, 114f.
sed, 312 declared, 115
stream, 312 initialized, lisf.
samples from atatisticil distributions, 313 Reference:
generating functions, 313, 314t array, 34
argument, 313 attribute:
example,nested, 22
used to generate activity times, 313 of perranent entity, 205
variables: of temporary entity, 203
construction of set, 322
declared, 316f. REGARDLESS statemcnt, 14; aee atoo ELSE statement
RANDOM LINEAR VARIABLE, 318 Relational operator, 5, 6t
RANDOM STEP VARIABLE, 317f.
defined, 316 Relative time specification, 301
example, 348, 352 Relative location of attribute, 195
free-form READ, 320, 322
input format, 320 RELEASE statement:
prohibited use, 319 for arrays, 110
sampling routines, 319t for attributes of permanent entities, 206
generation, 319 compound, 243
inhibition, 319 for routines, 140
set, 320 REMOVE statement, 225
stored, 320 FIRST, 231
RANDOM.E entity, 320, 369t LAST, 231
specific, 231
RANDOM.F function, 312f., 369t THIS, 231
Range of FOR statement, 44-45, 52 ABOVE, 231
used in BEFORE and AFTER statements, 323t
Ranked set, 233 REPEAT rtatement, 52
Ranking function example, 250 Report:
RCOLUMN.V system variable, 369t generator, 179
defined, 177 column repetition, 185
set by external event, 310 DOUBLE LINES, 184f.
Read binary, 175 roy repetition, 179-181
SUPPRESSING clause, 190
READ statement: section, 179
formatted: headings:
controlled, 170f. printing on each page, l6
defined, 157 printing on first page only, 182
descriptors, 158-168 NEW PAGE, 183
TEXT, 273
unit specification, 172 Required set attributes, 2It
variable formats, 171 RESCHEDULE statement, 298; cee alco Scheduling
free-form: RESERVE statement:
ALPHA, 152 defined, 37-40
for arrays, 48ff. general form, 64f.
defined, 6f. multiple form, 60
card format, 7 pointer words only, 65
controlled, 50
look-ahead properties, 76, 77t RESET statement, 332f.
RANDOM variables, 320 RESUME SUBSTITUTION statement, 121
TEXT, 272
unit specification, 172 RETURN statement:
READV system variable, 369t in an event routine, 308
ReAVsem,vai e used in a function, 93
defined, 155usdn preue,9
set by external event, 310f. used in a procedure, 99

REAL, 2 REVERSE ORDER phrase, 239


defined, 30 REWIND statement, 17s
format descriptors (0, E), 159, 160 Right-handed function, 259f.
input conversion, 32t
mode conversion, 91t, 276 RINF.C constant, 79t, 369t
RANDOM LINEAR variables, 318 R.nwe routine, 332
see aloo Decimal
REAL.F function, 91t, 276, 369t Rounding:
In D format, 159
Record, 156 input conversions, 32t
in library functions (INT.F), 9It
Recursion concept, 113 output conversions, 19t
in mode conversions, 33
-382-

Routine (Procedure): Set (con-tnued):


arguments: definition statement, 233
array pointers, 103f. example, 338
input, 9s FILE'statement, 225ff.
output, 99f. initial condition, 225
correct number, 101 logical expressions, 232
CALL. 100 member, 196
defined, 99 membership clause, 200
DYNAMIC, 143f. modification example, 348
generated by system: name, 201
to file events, 295f. operation codes, 259
to initialize counters, 332 organization, 198
to manipulate sete, 258t ovner, 196
tj perform sampling procedures. 319t ovnership clause, 200
timing for simulation, 294ff. pointers, 196f.
monitored, 263f. properties, 224
recursive. 113t. ranking, 233
RELEASE, 140f. REMOVE statement, 230f,
RETURN, 99 routines:
statement, 83 defined, 257, 258t
of the system, 369t deletion, 255f.
used as both a function and a procedure, 102f. of the system, 369t; see also EV.S set
Row repetition, 179-181 used for RANDOM sampling, 320
RSTEP.F function. 319t. 369t EV.S attribute, 369t
external event, 292
RVALUE.A attribute, 320, 369t internal event, 288
R.uw'vab routine, 332 packing rules, 299
SFIELD.F function, 77, 91t, 369t
S format, 168 Side effects:
Same time specification, 303 of functions, 113
Sampling package, 312f., 314t of global variables, 112

SAVE: SIGN.F funrtion, 91t, 369t


event notice (SAVING phrase), 311 Significanc figures, 75
routine (SAVE statement), 143f. Simple expressions. 3
SAVED: Simulation:
varined,: . basic unit of action (activity), 282f,
defined, 114!. central concept (eve.t), 282f.
Initialization, 116 clock, 283
local array, 357 continuous time, 283
local variables, 115 control, 293f., 364
Scale factor in E format, 160 defined, 281
Scheduling, 285, 364 discrete event, 281, 283
internal events, 296ff. end of, 294
removal of event, 303f. example, 336-357
statement: initialization, 294
vith arguments, 299f. languages, 364
using AT phrases, 298f. START statement, 294, 304
using IN phrases, 302f. time, 282f.
using NOW or NEXT phrases. 303 Simultaneous events, 284
using previously created event notice, 298
synonyms, 298 SIN.F function, 91t, 369t
used in BEFORE anj AFTER statements (CAUSE), 323t SKIP statement:
Scientific notation: defined, 7f.
conversion in LIST statement, 74f., 74n, 75n FIELDS, 8
eormat conventions, l11t INPUT CARDS, 9f.
format descriptor, 160 OUTPUT LINES, 20
Sea.!ch: Slash (/) in format, 168
statement to perform (FIND), 145f.
SEED.V system array, 312, 369t phen required, 11
Selection clauses, 137f., 236f. Special:
Sequencing programs, 129f. characters, 10
Set: vords, 29
attributes, 196ff., 224 SQRT.F function, 91t, 369t
deletion, 234
required, 241 S.eat attribute, 197, 224
construction for RANDOM sampling, 320 SSQ statistic, ase SUM.OF.SQUARES statistic
control phrase, 238f.
declaration, 223f. Standard deviation, see STD.DEV statistic
defined, 196 STO statistic, oee STD.DEV statistic
-383-

STD.DEV statistic: Successor-In-sat pointer, 224


ACCUMULATE statement, 329t SUM statistic:
COMPUTE statement, 149t ACCUMULATE statement, 329t
TALLY statement, 325t COMPUTE statement, 149t
Standard: TALLY statement, 325t
input unit. 155 SUM.OF.SQUARES statistic:
for extecnal events, 292 ACCUMULATE statement, 329t
output unit, 155 COMPUTE statement, 149t
START NEW CARD statement, 8 TALLY statement, 325t
START NEW PAGE statement, 20 SUPPRESS SUBSTITUTION statement, 121
SUPPRESSING clause, 190
START SIM)LATION statement: S attribute, 320
defined, 294
example, 350 Symbol table of TEXT, 272
scheduling external events, 304 Synchronous variables, 363
State of an entity, 194 Synonyms, 120
State probability estimation, 331f. System:
attributes:
dttefined 1defined, 207
defined, 1 dimension, 207
rules for, 11 clock, 283
Statement label, see Label -defined constant, 78, 79t
-defined values, 76
Static structure, 337 dynamics, 282, 293
Statistical: names, 369t
distributiono, 314t set, 207f.
phenomena, 312 THE S 'STEM statement, 207
Step sampling, 317
STOP statement, 20f. T format:
Storage: READ statement, 273
of arrays, 54 WRITE statement, 275
of attributes: Table look-up, 316f.
of permanent entities, 210 TALLY:
of the system, 211
of temporary entities, 210 actions, 325
of sampling data, 316f. computations, 329
of set pointers, 211 counters, 328
of TEXT, 272 initialization, 332f.
without conversion, 279 defined, 324
aee alaso inimizing storage DUMMY variable, 335
example, 339, 349
STORE statement, 279 statement, 324
components, 280t TAN.F function, 91t, 369t
Stream input, 6f., 272 Temporary entities:
Structure, 58 allocate storage (CREATE), 201
Subprogram: declaration, 201
body, 83 defined, 201f.
defined, 79 return storage (DESTROY), 204
definition statement, 82 example, 348
age also Function; Routine global variable, 201f.
identification number, 202
SUBPROGRAM: reference, 203
function calls, 269 statement, 201
variable:
defined, 267f. Terminal period2, 10, 229
direct use, 268 Termination clause, 137f., 236f.
indirect use, 268
initialized, 269 Termination of program:
literal, 267f. out of data, 13
STOP statement, 20
Subscript, 34 TEXT:
Subscripted: concatenation of, 273
attributes, 243 conversion, 276t
label, 68 declared, 272
sets, 243 defined, 272
varisble, 33 destroy, 274
initialization, 39 dictionary, 272, 274
ae aZlo Array example, 351
SUBSTITUTE statement, 123 input, 272f.
length. 275
SUBTRACT statement, 9f. list, 273
-384-

Text (eonianudd): Variable:


literal, 273 defined, If.
mode, 272 definition statement, 29ff.
output, 275 dimension, 35
THE BUFFER, 178 forbidden form, 29, 29n
global, 84
THE SYSTEM statement, 207 initialized, 2
THEN BY clause, 233, 290 local, 84
mode, 29f., 150, 272
THEN IF statement, 131 monitored, 262
THUS phrase, 17 name, If., 28
name list, 6
Time: normal mode, 30
between events, 282 RANDO4, 316
conversion functions, 302t, 307t of the system. 369t
expression, 298, 300, 302t type, 115
formats, 305f. Variable formats, 171
origin. 306
series, 329 VARIANCE statistic:
at start of simulation, 301, 306 ACCUMULATE statement, 329t
in state, 132 COMPUTE statement, 149t
units, 301 TALLY statement, 325t
TIME.A attribute, 288, 369t
external 4vents, 292, 304 WCOLUMN.V system variable, 177, 369t
internal events, 299
WEEKDAY.F function,
302, 369t
Time-dependent behavior, 282
WEIBULL.F function, 314t, 369t
Time-dependent variable. 328
Timing:WHEN phrase, 138

routine, 283, 294 WHILE phrase, 137ff., 236f.


use of event notice, 287 WITH clause (set membership), 232
set , 288 WITH phrAse (logical control), 137ff., 236f.
TIME.V system variable, 301, 369t
set by external event, 310 WITHOUT ATTRIBUTES phrase, 234
initialized, 306 WITHOUT ROUTINES phrase, 259
set by internal event, 311
TRACE:Word, 120n

output, 361 WORD specification:


routine: defined, 219
example, 356 ,.xample, 348
statement, 360f., 362 rules, 221t
use of BEFORE and AFTER statements, 323t World view, 193
Transfer: Write binary, 175
computed GO TO, 66
GO TO, 13 WRITE statement:
IF statement, 13ff., 16, 131 attributes, 246f.
controlled, 170
True branch, 16 defined, 157f.
TRUNC.F function, 9It, 369t format descriptors, 158-169, 275
TTOA.F function, 276, 369t TEXT, 275
TYPE statement, 115 WRITE.V system veriable, 155, 369t

X.EV.S routine, 295f.


Unary operators, 3 X.ast routine, 258
Underscore (U character:.,
in ALPHA literal, 152
in TEXT literal, 273 YEAR.F function, 307, 369t
UNIFORM.F function, 314t. 369t YIELDING clause, 100
UNLESS phrase, 137, 139f., 236f. Y.set routine, 258
UNTIL phrase, 137, 139f., 236f.
Updating simulated time, 300
UPON statement, 287 Zero:
initialization to, 2, 39
USE statement, 154, 178 logical condition, 75
USING phrase, 172, r 175, 178,1time
362 suppression, 158f.
activities, 283

Z.EV.S routine, 295f.


VAR statistic, a2e VARIANCE statistic Z.80t routine, 258
DOCUMENT CONTROL DATA
1.ORIGINATING ACTIVITY 2a. REPORT SEURITY CLASSIFICATION
UNLST FT RD
THE RAND CORPORATION 2L4C!
3. REPORT TITLE
THE SIMSCRIPT II PROGRAMMING LANRZUAGE

4. AL'TIORCS) (Last name, first nameo,inhttal)

Kiviat, P. 3., R. Villanueva, H. M. Markowitz

5. RrPORT DATE Goa.TOTAL No. OF PAGES 1bNoOFRS.


October 1968 395 ---
7. CONTRACT OR GRANT No.
F44620-67-CI-0045 I &.ORIGINATOR'S
R-460-PR
REPORT No.

9a. AVAILABILITY/ LIMITATION NOTICES 9b. SPONSORING AGENCY


United Statee Air Force
DDC-1 Project RAND
* 1. ABSTRACT 11.KEY WORDS
-A user's and prograurner' s manual for SIMSCRIPT
SIMSCRIPT II that requires only a basic Computer simulation
knowledge of computers and programming Computer programming language
language translators (compilers). Sec-
tions that are unusually difficult or
contain features of limited use are marked
with an asterisk. The manual is divided
into Live chapters, corresponding to five
language'"levels.""' Level 1 is a teaching
language designed to introduce programming
concepts to nonprogrammers. Level 2 is
a language roughly comparable in pover
to FORTRAN, but departs from it in spe-
cific features. Level 3 is comparable in
power to ALGOL or PL/I, but with specific
differences, and contains information on
the new ALPILA mode for alpha-numeric
manipulations, on writing formatted re-
ports, and on internal editing. Level
4 contains the entity-attribute-set fea-
tures of SIMSCRIPT, which have been up-
dated and augmented to provide a more
powerful list-processing capability.
Level 5, thc simulation-oriented part of
SINSCRIPT II, contains statements for
time advance, event and activity process-
ing, gencration of statistical variates,
and accumulation and analysis of simula-
tion-generated data. Two new debugging
routines, BIEFORE and AFTER, enable the
monitoring of six complex processes. I

You might also like