1.8 About Functions

A program written in the GAP language is called a function. Functions are special GAP objects. Most of them behave like mathematical functions. They are applied to objects and will return a new object depending on the input. The function Factorial, for example, can be applied to an integer and will return the factorial of this integer.

    gap> Factorial(17);
    355687428096000 

Applying a function to arguments means to write the arguments in parentheses following the function. Several arguments are separated by commas, as for the function Gcd which computes the greatest common divisor of two integers.

    gap> Gcd(1234, 5678);
    2 

There are other functions that do not return a value but only produce a side effect. They change for example one of their arguments. These functions are sometimes called procedures. The function Print is only called for the side effect to print something on the screen.

    gap> Print(1234, "\n");
    1234 

In order to be able to compose arbitrary text with Print, this function itself will not produce a line break after printing. Thus we had another newline character "\n" printed to start a new line.

Some functions will both change an argument and return a value such as the function Sortex that sorts a list and returns the permutation of the list elements that it has performed.

You will not understand right now what it means to change an object. We will return to this subject several times in the next sections.

A comfortable way to define a function is given by the maps--to operator - consisting of a minus sign and a greater sign with no whitespace between them. The function cubed which maps a number to its cube is defined on the following line.

    gap> cubed:= x -> x^3;
    function ( x ) ... end 

After the function has been defined, it can now be applied.

    gap> cubed(5);
    125 

Not every GAP function can be defined in this way. You will see how to write your own GAP functions in a later section.

In this section you have seen GAP objects of type function. You have learned how to apply a function to arguments. This yields as result a new object or a side effect. A side effect may change an argument of the function. Moreover you have seen an easy way to define a function in GAP with the maps-to operator.

Procedure Calls. The functions of the GAP library are described in detail in the remaining chapters of this manual, the Reference Manual.

Previous Up Top Next
Index

GAP 3.4.4
April 1997