Goto Chapter: Top 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 Bib Ind
 [Top of Book]  [Contents]   [Previous Chapter]   [Next Chapter] 

5 Functions
 5.1 Information about a function
 5.2 Calling a function with a list argument that is interpreted as several arguments
 5.3 Wrapping a function, so the values produced are cached
 5.4 Functions that do nothing
 5.5 Function Types
 5.6 Naming Conventions

5 Functions

The section 4.23 describes how to define a function. In this chapter we describe functions that give information about functions, and various utility functions used either when defining functions or calling functions.

5.1 Information about a function

5.1-1 NameFunction
‣ NameFunction( func )( operation )

returns the name of a function. For operations, this is the name used in their declaration. For functions, this is the variable name they were first assigned to. (For some internal functions, this might be a name different from the name that is documented.) If no such name exists, the string "unknown" is returned.

gap> NameFunction(SylowSubgroup);
gap> Blubberflutsch:=x->x;;
gap> NameFunction(Blubberflutsch);
gap> a:=Blubberflutsch;;
gap> NameFunction(a);
gap> NameFunction(x->x);
gap> NameFunction(NameFunction);

5.1-2 NumberArgumentsFunction
‣ NumberArgumentsFunction( func )( operation )

returns the number of arguments the function func accepts. -1 is returned for all operations. For functions that use ... or arg to take a variable number of arguments, the number returned is -1 times the total number of parameters. For attributes, 1 is returned.

gap> NumberArgumentsFunction(function(a,b,c,d,e,f,g,h,i,j,k)return 1;end);
gap> NumberArgumentsFunction(Size);
gap> NumberArgumentsFunction(IsCollsCollsElms);
gap> NumberArgumentsFunction(Sum);
gap> NumberArgumentsFunction(function(a, x...) return 1; end);

5.1-3 NamesLocalVariablesFunction
‣ NamesLocalVariablesFunction( func )( operation )

returns a mutable list of strings; the first entries are the names of the arguments of the function func, in the same order as they were entered in the definition of func, and the remaining ones are the local variables as given in the local statement in func. (The number of arguments can be computed with NumberArgumentsFunction (5.1-2).)

gap> NamesLocalVariablesFunction(function( a, b ) local c; return 1; end);
[ "a", "b", "c" ]
gap> NamesLocalVariablesFunction(function( arg ) local a; return 1; end);
[ "arg", "a" ]
gap> NamesLocalVariablesFunction( Size );

5.1-4 FilenameFunc
‣ FilenameFunc( func )( function )

For a function func, FilenameFunc returns either fail or the absolute path of the file from which func has been read. The return value fail occurs if func is a compiled function or an operation. For functions that have been entered interactively, the string "*stdin*" is returned, see Section 9.5.

gap> FilenameFunc( LEN_LIST );  # a kernel function
gap> FilenameFunc( Size );      # an operation
gap> FilenameFunc( x -> x^2 );  # an interactively entered function
gap> meth:= ApplicableMethod( Size, [ Group( () ) ] );;
gap> FilenameFunc( meth );
"... some path .../"

5.1-5 StartlineFunc
‣ StartlineFunc( func )( function )
‣ EndlineFunc( func )( function )

Let func be a function. If FilenameFunc (5.1-4) returns fail for func then also StartlineFunc returns fail. If FilenameFunc (5.1-4) returns a filename for func then StartlineFunc returns the line number in this file where the definition of func starts.

EndlineFunc behaves similarly and returns the line number in this file where the definition of func ends.

gap> meth:= ApplicableMethod( Size, [ Group( () ) ] );;
gap> FilenameFunc( meth );
"... some path ... gap4r5/lib/"
gap> StartlineFunc( meth );
gap> EndlineFunc( meth );

5.1-6 LocationFunc
‣ LocationFunc( func )( function )

Let func be a function. Returns a string describing the location of func, or an empty string if the information cannot be found. This uses the information provided by FilenameFunc (5.1-4) and StartlineFunc (5.1-5)

gap> LocationFunc( Intersection );
"... some path ... gap/lib/"
# String is an attribute, so no information is stored
gap> LocationFunc( String );

5.1-7 PageSource
‣ PageSource( func[, nr] )( function )

This shows the file containing the source code of the function or method func in a pager (see Pager (2.4-1)). The display starts at a line shortly before the code of func.

For operations func the function shows the source code of the declaration of func. Operations can have several declarations, use the optional second argument to specify which one should be shown (in the order the declarations were read); the default is to show the first.

For kernel functions the function tries to show the C source code.

If GAP cannot find a file containing the source code this will be indicated.

Usage examples:
met := ApplicableMethod(\^, [(1,2),2743527]); PageSource(met);
PageSource(Size, 2);
ct := CharacterTable(Group((1,2,3)));
met := ApplicableMethod(Size,[ct]); PageSource(met);

5.2 Calling a function with a list argument that is interpreted as several arguments

5.2-1 CallFuncList
‣ CallFuncList( func, args )( operation )
‣ CallFuncListWrap( func, args )( operation )

returns the result, when calling function func with the arguments given in the list args, i.e. args is "unwrapped" so that args appears as several arguments to func.

gap> CallFuncList(\+, [6, 7]);
gap> #is equivalent to:
gap> \+(6, 7);

A more useful application of CallFuncList is for a function g that is called in the body of a function f with (a sublist of) the arguments of f, where f has been defined with a single formal argument arg (see 4.23), as in the following code fragment.

f := function ( arg )
       CallFuncList(g, arg);

In the body of f the several arguments passed to f become a list arg. If g were called instead via g( arg ) then g would see a single list argument, so that g would, in general, have to "unwrap" the passed list. The following (not particularly useful) example demonstrates both described possibilities for the call to g.

gap> PrintNumberFromDigits := function ( arg )
>     CallFuncList( Print, arg );
>     Print( "\n" );
>    end;
function( arg... ) ... end
gap> PrintNumberFromDigits( 1, 9, 7, 3, 2 );
gap> PrintDigits := function ( arg )
>     Print( arg );
>     Print( "\n" );
>    end;
function( arg... ) ... end
gap> PrintDigits( 1, 9, 7, 3, 2 );
[ 1, 9, 7, 3, 2 ]

CallFuncListWrap differs only in that the result is a list. This returned list is empty if the called function returned no value, else it contains the returned value as it's single member. This allows wrapping functions which may, or may not return a value.

gap> CallFuncListWrap( x -> x, [1] );
[ 1 ]
gap> CallFuncListWrap( function(x) end, [1] );
[ ]

5.3 Wrapping a function, so the values produced are cached

5.3-1 MemoizePosIntFunction
‣ MemoizePosIntFunction( function[, options] )( function )

MemoizePosIntFunction returns a function which behaves the same as function, except it caches the results; if the new function is called with the same input, then any call after the first will return the cached value, instead of recomputing it. The cache is flushed by calling FlushCaches (79.18-18).

The returned function will only accept positive integers.

This function does not promise to never call function more than once for any input -- values may be removed if the cache gets too large, or GAP chooses to flush all caches, or if multiple threads try to calculate the same value simultaneously.

The optional second argument is a record which provides a number of configuration options. The following options are supported.

defaults (default an empty list)

Used to initalise the cache, both initially and after each flush.

flush (default true)

If this is true, the cache is emptied whenever FlushCaches (79.18-18) is called.

errorHandler (defaults to Error (6.6-1))

A function to be called when an input which is not a positive integer is passed to the cache. If this function returns a value, that value is returned by the cache.

gap> f := MemoizePosIntFunction(
>           function(i) Print("Check: ",i,"\n"); return i*i; end,
>           rec(defaults := [,,50], errorHandler := x -> "Bad") );;
gap> f(2);
Check: 2
gap> f(2);
gap> f(3);
gap> f(-3);
gap> FlushCaches();
gap> f(2);
Check: 2
gap> f(3);

5.4 Functions that do nothing

The following functions return fixed results (or just their own argument). They can be useful in places when the syntax requires a function, but actually no functionality is required. So ReturnTrue (5.4-1) is often used as family predicate in InstallMethod (78.2-1).

5.4-1 ReturnTrue
‣ ReturnTrue( ... )( function )

This function takes any number of arguments, and always returns true.

gap> f:=ReturnTrue;  
function( arg... ) ... end
gap> f();  
gap> f(42);

5.4-2 ReturnFalse
‣ ReturnFalse( ... )( function )

This function takes any number of arguments, and always returns false.

gap> f:=ReturnFalse;  
function( arg... ) ... end
gap> f();  
gap> f("any_string");

5.4-3 ReturnFail
‣ ReturnFail( ... )( function )

This function takes any number of arguments, and always returns fail.

gap> oops:=ReturnFail;  
function( arg... ) ... end
gap> oops();  
gap> oops(-42);  

5.4-4 ReturnNothing
‣ ReturnNothing( ... )( function )

This function takes any number of arguments, and always returns nothing.

gap> n:=ReturnNothing;
function( object... ) ... end
gap> n();
gap> n(-42);

5.4-5 ReturnFirst
‣ ReturnFirst( ... )( function )

This function takes one or more arguments, and always returns the first argument. IdFunc (5.4-6) behaves similarly, but only accepts a single argument.

gap> f:=ReturnFirst;
function( object... ) ... end
gap> f(1);
gap> f(2,3,4);
gap> f();
Error, RETURN_FIRST requires one or more arguments

5.4-6 IdFunc
‣ IdFunc( obj )( function )

returns obj. ReturnFirst (5.4-5) is similar, but accepts one or more arguments, returning only the first.

gap> id:=IdFunc;  
function( object ) ... end
gap> id(42);  
gap> f:=id(SymmetricGroup(3));                 
Sym( [ 1 .. 3 ] )
gap> s:=One(AutomorphismGroup(SymmetricGroup(3)));
IdentityMapping( Sym( [ 1 .. 3 ] ) )
gap> f=s;

5.5 Function Types

Functions are GAP objects and thus have categories and a family.

5.5-1 IsFunction
‣ IsFunction( obj )( category )

is the category of functions.

gap> IsFunction(x->x^2);
gap> IsFunction(Factorial);
gap> f:=One(AutomorphismGroup(SymmetricGroup(3)));
IdentityMapping( Sym( [ 1 .. 3 ] ) )
gap> IsFunction(f);         

5.5-2 IsOperation
‣ IsOperation( obj )( category )

is the category of operations. Every operation is a function, but not vice versa.

gap> MinimalPolynomial;  
<Operation "MinimalPolynomial">
gap> IsOperation(MinimalPolynomial);
gap> IsFunction(MinimalPolynomial);         
gap> Factorial;
function( n ) ... end
gap> IsOperation(Factorial);

5.5-3 FunctionsFamily
‣ FunctionsFamily( family )

is the family of all functions.

5.6 Naming Conventions

The way functions are named in GAP might help to memorize or even guess names of library functions.

If a variable name consists of several words then the first letter of each word is capitalized.

If the first part of the name of a function is a verb then the function may modify its argument(s) but does not return anything, for example Append (21.4-5) appends the list given as second argument to the list given as first argument. Otherwise the function returns an object without changing the arguments, for example Concatenation (21.20-1) returns the concatenation of the lists given as arguments.

If the name of a function contains the word "Of" then the return value is thought of as information deduced from the arguments. Usually such functions are attributes (see 13.5). Examples are GeneratorsOfGroup (39.2-4), which returns a list of generators for the group entered as argument, or DiagonalOfMat (24.12-1).

For the setter and tester functions of an attribute Attr the names SetAttr resp. HasAttr are available (see 13.5).

If the name of a function contains the word "By" then the return value is thought of as built in a certain way from the parts given as arguments. For example, creating a group as a factor group of a given group by a normal subgroup can be done by taking the image of NaturalHomomorphismByNormalSubgroup (39.18-1). Other examples of "By" functions are GroupHomomorphismByImages (40.1-1) and LaurentPolynomialByCoefficients (66.13-1).

Often such functions construct an algebraic structure given by its generators (for example, RingByGenerators (56.1-4)). In some cases, "By" may be replaced by "With" (like e.g. GroupWithGenerators (39.2-3)) or even both versions of the name may be used. The difference between StructByGenerators and StructWithGenerators is that the latter guarantees that the GeneratorsOfStruct value of the result is equal to the given set of generators (see 31.3).

If the name of a function has the form "AsSomething" then the return value is an object (usually a collection which has the same family of elements), which may, for example:

If Something and the argument of AsSomething are domains, some further rules apply as explained in Tutorial: Changing the Structure.

If the name of a function fun1 ends with "NC" then there is another function fun2 with the same name except that the NC is missing. NC stands for "no check". When fun2 is called then it checks whether its arguments are valid, and if so then it calls fun1. The functions SubgroupNC (39.3-1) and Subgroup (39.3-1) are a typical example.

The idea is that the possibly time consuming check of the arguments can be omitted if one is sure that they are unnecessary. For example, if an algorithm produces generators of the derived subgroup of a group then it is guaranteed that they lie in the original group; Subgroup (39.3-1) would check this, and SubgroupNC (39.3-1) omits the check.

Needless to say, all these rules are not followed slavishly, for example there is one operation Zero (31.10-3) instead of two operations ZeroOfElement and ZeroOfAdditiveGroup.

 [Top of Book]  [Contents]   [Previous Chapter]   [Next Chapter] 
Goto Chapter: Top 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 Bib Ind

generated by GAPDoc2HTML