In a language like Pascal, a function is a piece of `packaged' program for performing standard operations like finding square roots. To obtain the square root of a positive number stored in a variable x, we write:
sqrt ( x )
at the point in the program where we want the value, such as:
writeln ( 1.0 + sqrt ( x ) ) ;
this is called an application of the function. The value represented by x
is called the argument or actual parameter. In this context, the canned
program computes the square root of x, 1.0 is added to it and the result
is then printed.
We can also define our own functions specifying how the result is computed using ordinary Pascal statements. Here's a function that returns the greater of its two argument values:
function max ( x, y : INTEGER ) : INTEGER ;
begin
if x > y
then max := x
else max := y
end ;
The identifiers x and y are called formal parameters. They're used
inside the definition to name the two values that will be supplied as
arguments when the function is applied. We can use max anywhere we need a
value, just like sqrt. Here's how we might use max to filter out
negative values on output:
writeln ( max ( z, 0 ) ) ;
A more interesting case is when the actual parameter is a function
application itself or involves one. We can use max to find the largest of
three numbers by writing:
max ( a, max ( b, c ) )
Combining functions together like this is called composition. The expression
is evaluated `inside-out' because the outer application of max can't be
evaluated until the value of its second argument is known. The inner
application of max is therefore evaluated first using the values of b and
c and the result is used as the actual parameter of the outer application.
Another way of combining functions together is to define more powerful ones using simpler ones as `building blocks'. If we often need to find the largest of three numbers we might define:
function MaxOf3 ( x, y, z : INTEGER ) : INTEGER ;
begin
MaxOf3 := max ( x, max ( y, z ) )
end ;
and apply it by writing:
MaxOf3 ( a, b, c )