Function
Function
By: GAP
function( [ arg-ident {, arg-ident} ] )
[local loc-ident {, loc-ident} ; ]
statements
end
A function is in fact a literal and not a statement. Such a function literal can be assigned
to a variable or to a list element or a record component. Later this function can be called
as described in Function Calls.
Because for each of the formal arguments arg-ident and for each of the formal
locals loc-ident a new variable is allocated when the function is called (see Function
Calls), it is possible that a function calls itself. This is usually called recursion. The
following is a recursive function that computes values of the Fibonacci sequence
Note that the recursive version needs 2 * fib(n)-1 steps to compute fib(n), while
the iterative version of fib needs only n-2 steps. Both are not optimal however, the
library function Fibonacci only needs about Log(n) steps.
As noted in Section Function Calls, the case where a function is defined with exactly
one formal argument with the name arg, is special. It provides a way of defining a
function with a variable number of arguments; the values of all the actual arguments are
stored in a list and this list is assigned to the new variable corresponding to the formal
argument arg. There are two typical scenarios for wanting such a possibility: having
optional arguments and having any number of arguments.
The following example shows one way that the function Position (see Position) might
be encoded and demonstrates the ``optional argument'' scenario.
The user should compare the above with the GAP function Sum (see Sum) which, for
example, may take a list argument and optionally an initial element (which zero should
the sum of an empty list return?).
arg-ident must be a single identifier, i.e., it is not possible to write functions of several
arguments this way. Also arg is not treated specially, so it is also impossible to write
functions that take a variable number of arguments this way.
This feature should be used rarely, since its implementation in GAP is not very
efficient.
Reference: http://www.gap-system.org/Manuals//doc/htm/ref/CHAP004.htm#SECT022
Date:10-9-2008