next up previous contents
Next: Lists and Arrays Revisited Up: Procedures Previous: Nested Routines

Variable Number of Arguments

All of the examples of procedures we have seen thus far have taken some fixed number of arguments: IsItPrime accepts a single positive integer, VectorVariance accepts an array of real values. However, it is sometimes convenient to create routines which accept a variable number of arguments of any type. This is especially useful if we do not know a priori how many items of data the user may pass to the routine or of which type these items will be.

There are two Darwin system variables made available to the user to enable them to determine the number of parameters passed to the routine and to read the list of parameters passed to the procedure. The first is nargs (number of arguments) of type real and the second is args (arguments) which is an expression sequence containing the entire argument list passed to the routine. A third name procname stores the name of the routine.

 
> PrintArguments := proc( )
>   lprint('The name of this procedure is: ', procname);
>   lprint('The number of arguments is: ', nargs);
>   lprint('The arguments are: ', args);
>   lprint();
>   for i from 1 to nargs do
>     lprint('Argument #', i, ': ', args[i]);
>   od;
> end;

> PrintArguments(1, 'hello', [3,4,5]);

The name of this procedure is:  print_arguments
The number of arguments is:  3
The arguments are:  1, hello, [3, 4, 5]

Argument # 1 :  1
Argument # 2 :  hello
Argument # 3 :  [3, 4, 5]
Notice that the formal argument (or formal parameter) list is empty. All parameters to this procedure are assigned to the name args.

As an example application, we create a function minimum which accepts any number of real values and returns the smallest one.

> minimum := proc( )
>   local smallest;
>   description 'Find the minimum of an arbitrary long list of real values';
>
>   for i from 1 to nargs do
>     if not (type(args[i], real)) then
>       lprint('An error in function ', procname);
>       error('A non real value passed as a parameter');
>     fi;
>   od;
    
>   smallest := args[1];       # initialize it to the first element of the list
>   for i from 2 to nargs do
>     if (args[i]<smallest) then
>       smallest := args[i];
>     fi;
>   od;
>   return(smallest);
> end:

> minimum(1, 2, 3, 4);
1
> minimum(a, 9, 10, 11);                    # an error
An error in function  minimum
Error, (in minimum) A non real value passed as a parameter
Note that we must perform our type checking inside of the body of the function.


next up previous contents
Next: Lists and Arrays Revisited Up: Procedures Previous: Nested Routines
Gaston Gonnet
1998-09-15