Writing a function that prints hello, world. on the screen is a simple
exercise in GAP.
gap> sayhello:= function()
> Print("hello, world.\n");
> end;
function ( ) ... end
This function when called will only execute the Print statement in the
second line. This will print the string hello, world. on the screen
followed by a newline character \n that causes the GAP prompt to
appear on the next line rather than immediately following the printed
characters.
The function definition has the following syntax.
arguments ) statements end
A function definition starts with the keyword function followed by
the formal parameter list arguments enclosed in parenthesis '( )'.
The formal parameter list may be empty as in the example. Several
parameters are separated by commas. Note that there must be no
semicolon behind the closing parenthesis. The function definition is
terminated by the keyword end.
A GAP function is an expression like an integer, a sum or a list.
Therefore it may be assigned to a variable. The terminating semicolon
in the example does not belong to the function definition but
terminates the assignment of the function to the name sayhello.
Unlike in the case of integers, sums, and lists the value of the
function sayhello is echoed in the abbreviated fashion function ( )
... end. This shows the most interesting part of a function: its
formal parameter list (which is empty in this example). The complete
value of sayhello is returned if you use the function Print.
gap> Print(sayhello, "\n");
function ( )
Print( "hello, world.\n" );
return;
end
Note the additional newline character "\n" in the Print
statement. It is printed after the object sayhello to start a new
line. The extra return statement is inserted by GAP to simplify
the process of executing the function.
The newly defined function sayhello is executed by calling sayhello()
with an empty argument list.
gap> sayhello(); hello, world.
However, this is not a typical example as no value is returned but only a string is printed.
GAP 4 manual