[GAP Forum] Default Arguments
Alexander Konovalov
alexander.konovalov at st-andrews.ac.uk
Tue Feb 9 21:57:58 GMT 2016
Dear Kieran,
> On 5 Feb 2016, at 08:54, Kieran Roberts <kroberts at math.uni-bielefeld.de> wrote:
>
> Dear GAP forum:
>
> Is it possible to include default arguments in a function?
>
> Such as something like this (which doesn't work):
>
> add := function(a,b:=1)
> return a+b;
> end;
>
> So that add(2,2) = 4 and add(2) = 3. The only way I've managed to do
> is by writing:
>
> add := function(arg)
> if Size(arg) = 2 then
> return arg[1] + arg[2];
> else
> return arg[1] + 1;
> fi;
> end;
>
> But if you have 2 or 3 (optional) arguments with default values this
> becomes cumbersome. Is there a more efficient way?
This will a bit easier in coming soon GAP 4.8: as written at
https://github.com/gap-system/gap/wiki/Changes-between-GAP-4.7-and-GAP-4.8
it will have "support for partially variadic functions to allow function
expressions like
function(a,b,c,x...) ... end;
which would require at least three arguments and assign the first three to
a, b and c and then a list containing any remaining ones to x. The former
special meaning of the argument arg is still supported and is now equivalent
to function(arg...), so no changes in the existing code are required."
The example from above could then look like
gap> add := function(a,b...)
> if Length(b)=0 then
> return a+1;
> else
> return a+b[1];
> fi;
> end;
function( a, b... ) ... end
gap> add(2,2);
4
gap> add(2);
3
If you have more optional arguments, they would all go into the list b,
but since you would be no longer obliged to use the special name 'arg',
your code may be more readable because of using proper identifiers for
mandatory arguments.
Best wishes
Alexander
More information about the Forum
mailing list