Procedures
and
Functions
COMMENT Obviously the use of procedures
and
parameters
In
such a simple program
is
not
necessary but Imagine that each sub-task might be much more complex.
In
such a
situation the use of procedures would allow a modular build-up of the program with
testing at each stage. The above example merely illustrates the main notations
and
relationships of procedures.
Similarly the next example Illustrates the use of functions.
Note that
in
the previous example the procedures
walter
and compute both return exactly
one value. Rewrite the procedures as functions and show any other changes necessary
as a consequence
DEFine
FuNction waiter(dish)
cook
dish
RETurn compute(dlsh)
END
DEFine
DEFine
FuNction compute(dish)
LET
total = 0
FOR k
= 1
TO
3
LET
total = total + dish(k) *pnce(k)
END
FOR k
RETurn total
END
DEFine
The function call
to
walter
also takes a different form
LET
bi
IL
;
waiter(dish)
This program works as before. Notice that there are fewer parameters though the program
structure
is
similar That
IS
because the function names are also serving as parameters
retuning Information to the source of the function call.
EXAMPLE All the variables used as formal parameters
in
procedures or functions are
'safe'
because
they are automatically local. Which variables used
in
the procedures or functions are
not
locar
What additional statements would
be
needed
to
make them
locar
Program Changes The variables
k,
pick
and num are not local. The necessary changes
to
make them so are:
LOCAL k
LOCAL pick, num
•
•
92
TYPELESS
PARAMETERS
Program
Output
SCOPE
OF
VARIABLES
Formal parameters
do
not have any type.
You
may prefer that a variable which handles
numbers has the appearance of a numenc vanable
and
which handles stnngs looks
like a string variable,
but
however you write your parameters they are typeless.
To
prove
it,
try the
follOWing
program.
100
REMark
Number
or
word
110
waiter
2
120
waiter
"Chicken"
130
DEFine
PROCedure
waiter(item)
140
PRINT I
item
I
150
END
DEFine
2
Chi
eken
The type of the parameter
is
determined only when the procedure
is
called
and
an actual
parameter
'arrives:
Consider the
follOWing
program and try to consider what two numbers will
be
output.
100
REMark
scope
110
LET
number;
1
120
test
130
DEFine
PROCedure
test
140
LOCa
L
number
150
LET
number
= 2
160
PRINT
number
170
try
12/84
•
•